assign-gingerly 0.0.2 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -61,6 +61,176 @@ console.log(obj);
61
61
 
62
62
  When the right hand side of an expression is an object, assignGingerly is recursively applied (passing the third argument in if applicable, which will be discussed below)
63
63
 
64
+ ## Example 4 - Incrementing values with !inc command
65
+
66
+ The `!inc` command allows you to increment numeric values:
67
+
68
+ ```TypeScript
69
+ const obj = {
70
+ a: {
71
+ b: {
72
+ c: 2
73
+ }
74
+ }
75
+ };
76
+ assignGingerly(obj, {
77
+ '!inc ?.a?.b?.c': 3,
78
+ '!inc ?.a?.d?.e': -2
79
+ });
80
+ console.log(obj);
81
+ // {
82
+ // a: {
83
+ // b: { c: 5 }, // 2 + 3 = 5
84
+ // d: { e: -2 } // non-existent path created with value -2
85
+ // }
86
+ // }
87
+ ```
88
+
89
+ The `!inc` command syntax is `!inc <path>` where the path can use the `?.` nested notation. The right-hand side value is added to the existing value using `+=`. If the path doesn't exist, it's created and set directly to the value. Non-numeric increments will allow JavaScript to throw its natural error.
90
+
91
+ ## Example 5 - Toggling boolean values with !toggle command
92
+
93
+ The `!toggle` command allows you to toggle boolean values either immediately or after a delay:
94
+
95
+ ```TypeScript
96
+ const obj = {
97
+ a: {
98
+ b: {
99
+ c: true
100
+ }
101
+ }
102
+ };
103
+ assignGingerly(obj, {
104
+ '!toggle ?.a?.b?.c': 0, // Toggle immediately
105
+ '!toggle ?.a?.d?.e': 20 // Toggle after 20ms
106
+ });
107
+ console.log(obj);
108
+ // {
109
+ // a: {
110
+ // b: { c: false } // Toggled immediately
111
+ // // d doesn't exist yet
112
+ // }
113
+ // }
114
+
115
+ setTimeout(() => {
116
+ console.log(obj);
117
+ // {
118
+ // a: {
119
+ // b: { c: false },
120
+ // d: { e: true } // Created and toggled after 20ms
121
+ // }
122
+ // }
123
+ }, 40);
124
+ ```
125
+
126
+ The `!toggle` command syntax is `!toggle <path>` where the path can use the `?.` nested notation. The right-hand side value determines the behavior:
127
+ - **RHS = 0**: Toggle the existing value immediately (non-existent paths are not created)
128
+ - **RHS > 0**: Schedule the toggle to happen after N milliseconds (non-existent paths are created and initialized to `true`)
129
+
130
+ For existing values, the toggle is performed using JavaScript's logical NOT operator (`!value`). Non-numeric delay values will be passed to `setTimeout` and may throw an error.
131
+
132
+ ## Example 6 - Deleting properties with !delete command
133
+
134
+ The `!delete` command allows you to delete properties either immediately or after a delay:
135
+
136
+ ```TypeScript
137
+ const obj = {
138
+ a: {
139
+ b: {
140
+ c: true,
141
+ d: 'hello'
142
+ }
143
+ }
144
+ };
145
+ assignGingerly(obj, {
146
+ '!delete ?.a?.b?.c': 0, // Delete immediately
147
+ '!delete ?.a?.b': 20 // Delete after 20ms
148
+ });
149
+ console.log(obj);
150
+ // {
151
+ // a: {
152
+ // b: { d: 'hello' } // c deleted immediately
153
+ // }
154
+ // }
155
+
156
+ setTimeout(() => {
157
+ console.log(obj);
158
+ // {
159
+ // a: {} // b deleted after 20ms
160
+ // }
161
+ }, 40);
162
+ ```
163
+
164
+ The `!delete` command syntax is `!delete <path>` where the path can use the `?.` nested notation. The right-hand side value determines the behavior:
165
+ - **RHS = 0**: Delete the final property immediately (non-existent paths are silently skipped)
166
+ - **RHS > 0**: Schedule the deletion to happen after N milliseconds (non-existent paths are silently skipped)
167
+
168
+ **Important**: The `!delete` command only deletes the **final property** in the path. The entire nested chain is not deleted. For example, `'!delete ?.a?.b?.c': 0` only deletes property `c`, leaving the structure `a.b` intact. If any intermediate path doesn't exist, the command is silently skipped without error.
169
+
170
+ ## Example 7 - Reversible assignments with assignTentatively
171
+
172
+ The `assignTentatively` function works like `assignGingerly` but with a powerful addition: **reversibility**. It tracks changes and generates a reversal object that can undo all modifications:
173
+
174
+ ```TypeScript
175
+ import assignTentatively from 'assign-gingerly/assignTentatively';
176
+
177
+ const obj = { f: { g: 'hello' } };
178
+ const reversal = {};
179
+
180
+ assignTentatively(obj, {
181
+ '?.style?.height': '15px',
182
+ '?.a?.b?.c': {
183
+ d: 'hello',
184
+ e: 'world'
185
+ },
186
+ '?.f?.g': 'bye'
187
+ }, { reversal });
188
+
189
+ console.log(obj);
190
+ // {
191
+ // f: { g: 'bye' },
192
+ // style: { height: '15px' },
193
+ // a: { b: { c: { d: 'hello', e: 'world' } } }
194
+ // }
195
+
196
+ console.log(reversal);
197
+ // {
198
+ // '!delete ?.a': 0,
199
+ // '!delete ?.style': 0,
200
+ // '?.f?.g': 'hello'
201
+ // }
202
+
203
+ // Later, restore to original state:
204
+ assignTentatively(obj, reversal);
205
+ console.log(obj);
206
+ // {
207
+ // f: { g: 'hello' }
208
+ // }
209
+ ```
210
+
211
+ **Key differences from assignGingerly:**
212
+ - **No setTimeout support**: All `!toggle`, `!inc`, and `!delete` commands execute immediately, regardless of the RHS value
213
+ - **No registry/DI support**: Dependency injection features are not available (pass it in and it will be ignored)
214
+ - **Reversal tracking**: Maintains a reversal object that records:
215
+ - **Original values** of modified existing properties
216
+ - **!delete commands** for newly created top-level paths (e.g., `!delete ?.a` for paths created under `a`)
217
+ - **Original values** for deleted properties
218
+
219
+ **Reversal guarantee:**
220
+ ```JavaScript
221
+ const reversal = {};
222
+ const obj = {...originalObj};
223
+ const string1 = JSON.stringify(obj);
224
+
225
+ assignTentatively(obj, sourceChanges, { reversal });
226
+ assignTentatively(obj, reversal);
227
+
228
+ const string2 = JSON.stringify(obj);
229
+ console.log(string1 === string2); // true
230
+ ```
231
+
232
+ This guarantees that applying the reversal object restores the object to its exact original state.
233
+
64
234
  ## Dependency injection based on a registry object and a Symbolic reference
65
235
 
66
236
  ```Typescript
@@ -96,20 +266,18 @@ baseRegistry.push([
96
266
  map: {
97
267
  [isHappy]: 'isHappy'
98
268
  },
99
- spawn: MyEnhancement
269
+ spawn: MyEnhancement,
100
270
  },{
101
271
 
102
272
  map: {
103
273
  [isMellow]: 'isMellow'
104
274
  },
105
- spawn: async () => {
106
- return YourEnhancement;
107
- }
275
+ spawn: YourEnhancement,
108
276
  }
109
277
  ]);
110
278
  //end of dependency injection
111
279
 
112
- const asyncResult = await assignGingerly({}, {
280
+ const result = assignGingerly({}, {
113
281
  [isHappy]: true,
114
282
  [isMellow]: true,
115
283
  '?.style.height': '40px',
@@ -117,7 +285,7 @@ const asyncResult = await assignGingerly({}, {
117
285
  }, {
118
286
  registry: BaseRegistry
119
287
  });
120
- asyncResult.set[isMellow] = false;
288
+ result.set[isMellow] = false;
121
289
  ```
122
290
 
123
291
  The assignGingerly searches the registry for any items that has a mapping with a matching symbol of isHappy and isMellow, and if found, sees if it already has an instance of the spawn class associated with the first passed in parameter. If no such instance is found, it instantiates one, associates the instance with the first parameter, then sets the property value.
@@ -126,12 +294,10 @@ It also adds a lazy property to the first passed in parameter, "set", which retu
126
294
 
127
295
  The suggestion to use Symbol.for with a guid, as opposed to just Symbol(), is based on some negative experiences I've had with multiple versions of the same library being referenced, but is not required. Regular symbols could also be used when that risk can be avoided.
128
296
 
129
- Note that the example above is the first time we mention async. This is only necessary if you wish to work directly with the merged object. This allows for lazy loading of the spawning class, which can be useful for large applications that don't need to download all the classes at once. If you are just "depositing" values into the object, no need to await for anything. Also, the assignGingerly should first do all the class instantiations that are already loaded (where the class constructor is specified in spawn), and then does all the lazy loaded ones.
130
-
131
297
  ## Support for JSON assignment with Symbol.for symbols
132
298
 
133
299
  ```JavaScript
134
- const asyncResult = await assignGingerly({}, {
300
+ const result = assignGingerly({}, {
135
301
  "[Symbol.for('TFWsx0YH5E6eSfhE7zfLxA')]": true,
136
302
  "[Symbol.for('BqnnTPWRHkWdVGWcGQoAiw')]": true,
137
303
  '?.style.height': '40px',
@@ -46,6 +46,51 @@ function parseSymbolForKey(key) {
46
46
  }
47
47
  return null;
48
48
  }
49
+ /**
50
+ * Helper function to check if a key represents an !inc command
51
+ */
52
+ function isIncCommand(key) {
53
+ return key.startsWith('!inc ');
54
+ }
55
+ /**
56
+ * Helper function to parse an !inc command and extract the path
57
+ */
58
+ function parseIncCommand(key) {
59
+ if (!isIncCommand(key)) {
60
+ return null;
61
+ }
62
+ return key.substring(5); // Remove '!inc ' prefix
63
+ }
64
+ /**
65
+ * Helper function to check if a key represents a !toggle command
66
+ */
67
+ function isToggleCommand(key) {
68
+ return key.startsWith('!toggle ');
69
+ }
70
+ /**
71
+ * Helper function to parse a !toggle command and extract the path
72
+ */
73
+ function parseToggleCommand(key) {
74
+ if (!isToggleCommand(key)) {
75
+ return null;
76
+ }
77
+ return key.substring(8); // Remove '!toggle ' prefix
78
+ }
79
+ /**
80
+ * Helper function to check if a key represents a !delete command
81
+ */
82
+ function isDeleteCommand(key) {
83
+ return key.startsWith('!delete ');
84
+ }
85
+ /**
86
+ * Helper function to parse a !delete command and extract the path
87
+ */
88
+ function parseDeleteCommand(key) {
89
+ if (!isDeleteCommand(key)) {
90
+ return null;
91
+ }
92
+ return key.substring(8); // Remove '!delete ' prefix
93
+ }
49
94
  /**
50
95
  * Helper function to parse a path string with ?. notation
51
96
  */
@@ -77,7 +122,7 @@ function ensureNestedPath(obj, pathParts) {
77
122
  /**
78
123
  * Main assignGingerly function
79
124
  */
80
- export async function assignGingerly(target, source, options) {
125
+ export function assignGingerly(target, source, options) {
81
126
  if (!target || typeof target !== 'object') {
82
127
  return target;
83
128
  }
@@ -86,8 +131,6 @@ export async function assignGingerly(target, source, options) {
86
131
  : options?.registry
87
132
  ? new options.registry()
88
133
  : undefined;
89
- // Track promises for async spawning
90
- const asyncSpawns = [];
91
134
  // Convert Symbol.for string keys to actual symbols
92
135
  const processedSource = {};
93
136
  for (const key of Object.keys(source)) {
@@ -112,6 +155,111 @@ export async function assignGingerly(target, source, options) {
112
155
  // First pass: handle all non-symbol keys and sync operations
113
156
  for (const key of Object.keys(processedSource)) {
114
157
  const value = processedSource[key];
158
+ // Handle !inc commands
159
+ if (isIncCommand(key)) {
160
+ const path = parseIncCommand(key);
161
+ if (path) {
162
+ const pathParts = parsePath(path);
163
+ const lastKey = pathParts[pathParts.length - 1];
164
+ const parent = ensureNestedPath(target, pathParts);
165
+ // If the path doesn't exist, set it directly to the value
166
+ if (!(lastKey in parent)) {
167
+ parent[lastKey] = value;
168
+ }
169
+ else {
170
+ // Path exists, apply increment: oldValue += newValue
171
+ parent[lastKey] += value;
172
+ }
173
+ }
174
+ continue;
175
+ }
176
+ // Handle !toggle commands
177
+ if (isToggleCommand(key)) {
178
+ const path = parseToggleCommand(key);
179
+ if (path) {
180
+ const delay = value;
181
+ if (delay === 0) {
182
+ // Immediate toggle
183
+ const pathParts = parsePath(path);
184
+ const lastKey = pathParts[pathParts.length - 1];
185
+ const parent = ensureNestedPath(target, pathParts);
186
+ if (lastKey in parent) {
187
+ // Path exists, toggle it
188
+ parent[lastKey] = !parent[lastKey];
189
+ }
190
+ // If path doesn't exist, don't create it for immediate toggle
191
+ }
192
+ else {
193
+ // Delayed toggle using setTimeout
194
+ setTimeout(() => {
195
+ const pathParts = parsePath(path);
196
+ const lastKey = pathParts[pathParts.length - 1];
197
+ const parent = ensureNestedPath(target, pathParts);
198
+ if (lastKey in parent) {
199
+ // Path exists, toggle it
200
+ parent[lastKey] = !parent[lastKey];
201
+ }
202
+ else {
203
+ // Path doesn't exist, initialize to true
204
+ parent[lastKey] = true;
205
+ }
206
+ }, delay);
207
+ }
208
+ }
209
+ continue;
210
+ }
211
+ // Handle !delete commands
212
+ if (isDeleteCommand(key)) {
213
+ const path = parseDeleteCommand(key);
214
+ if (path) {
215
+ const delay = value;
216
+ if (delay === 0) {
217
+ // Immediate delete
218
+ const pathParts = parsePath(path);
219
+ if (pathParts.length > 0) {
220
+ const lastKey = pathParts[pathParts.length - 1];
221
+ const parentPathParts = pathParts.slice(0, -1);
222
+ // Navigate to parent without creating intermediate paths
223
+ let parent = target;
224
+ let canDelete = true;
225
+ for (const part of parentPathParts) {
226
+ if (!(part in parent) || typeof parent[part] !== 'object' || parent[part] === null) {
227
+ canDelete = false;
228
+ break;
229
+ }
230
+ parent = parent[part];
231
+ }
232
+ if (canDelete && lastKey in parent) {
233
+ delete parent[lastKey];
234
+ }
235
+ }
236
+ }
237
+ else {
238
+ // Delayed delete using setTimeout
239
+ setTimeout(() => {
240
+ const pathParts = parsePath(path);
241
+ if (pathParts.length > 0) {
242
+ const lastKey = pathParts[pathParts.length - 1];
243
+ const parentPathParts = pathParts.slice(0, -1);
244
+ // Navigate to parent without creating intermediate paths
245
+ let parent = target;
246
+ let canDelete = true;
247
+ for (const part of parentPathParts) {
248
+ if (!(part in parent) || typeof parent[part] !== 'object' || parent[part] === null) {
249
+ canDelete = false;
250
+ break;
251
+ }
252
+ parent = parent[part];
253
+ }
254
+ if (canDelete && lastKey in parent) {
255
+ delete parent[lastKey];
256
+ }
257
+ }
258
+ }, delay);
259
+ }
260
+ }
261
+ continue;
262
+ }
115
263
  if (isNestedPath(key)) {
116
264
  const pathParts = parsePath(key);
117
265
  const lastKey = pathParts[pathParts.length - 1];
@@ -121,7 +269,7 @@ export async function assignGingerly(target, source, options) {
121
269
  if (!(lastKey in parent) || typeof parent[lastKey] !== 'object') {
122
270
  parent[lastKey] = {};
123
271
  }
124
- await assignGingerly(parent[lastKey], value, options);
272
+ assignGingerly(parent[lastKey], value, options);
125
273
  }
126
274
  else {
127
275
  parent[lastKey] = value;
@@ -133,7 +281,7 @@ export async function assignGingerly(target, source, options) {
133
281
  if (!(key in target) || typeof target[key] !== 'object') {
134
282
  target[key] = {};
135
283
  }
136
- await assignGingerly(target[key], value, options);
284
+ assignGingerly(target[key], value, options);
137
285
  }
138
286
  else {
139
287
  target[key] = value;
@@ -155,8 +303,7 @@ export async function assignGingerly(target, source, options) {
155
303
  // Check if instance already exists
156
304
  let instance = instances.get(sym);
157
305
  if (!instance) {
158
- // Check if spawn is a constructor or a promise
159
- const SpawnClass = await Promise.resolve(registryItem.spawn);
306
+ const SpawnClass = registryItem.spawn;
160
307
  instance = new SpawnClass();
161
308
  instances.set(sym, instance);
162
309
  }
@@ -184,31 +331,12 @@ export async function assignGingerly(target, source, options) {
184
331
  let instance = instances.get(prop);
185
332
  if (!instance) {
186
333
  const SpawnClass = registryItem.spawn;
187
- if (SpawnClass instanceof Promise) {
188
- // Handle async case - would need to be awaited externally
189
- SpawnClass.then((SC) => {
190
- instance = new SC();
191
- instances.set(prop, instance);
192
- const mappedKey = registryItem.map[prop];
193
- if (mappedKey && instance && typeof instance === 'object') {
194
- instance[mappedKey] = value;
195
- }
196
- });
197
- }
198
- else {
199
- instance = new SpawnClass();
200
- instances.set(prop, instance);
201
- const mappedKey = registryItem.map[prop];
202
- if (mappedKey && instance && typeof instance === 'object') {
203
- instance[mappedKey] = value;
204
- }
205
- }
334
+ instance = new SpawnClass();
335
+ instances.set(prop, instance);
206
336
  }
207
- else {
208
- const mappedKey = registryItem.map[prop];
209
- if (mappedKey && instance && typeof instance === 'object') {
210
- instance[mappedKey] = value;
211
- }
337
+ const mappedKey = registryItem.map[prop];
338
+ if (mappedKey && instance && typeof instance === 'object') {
339
+ instance[mappedKey] = value;
212
340
  }
213
341
  }
214
342
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "assign-gingerly",
3
- "version": "0.0.2",
3
+ "version": "0.0.3",
4
4
  "description": "This package provides a utility function for carefully merging one object into another.",
5
5
  "homepage": "https://github.com/bahrus/assign-gingerly#readme",
6
6
  "bugs": {
@@ -13,20 +13,20 @@
13
13
  "license": "MIT",
14
14
  "author": "Bruce B. Anderson <andeson.bruce.b@gmail.com>",
15
15
  "type": "module",
16
- "types": "index.d.ts",
16
+ "types": "types.d.ts",
17
17
  "files": [
18
- "index.js",
18
+ "assignGingerly.js",
19
19
  "index.d.ts",
20
20
  "README.md",
21
21
  "LICENSE"
22
22
  ],
23
23
  "exports": {
24
24
  ".": {
25
- "import": "./index.js",
26
- "types": "./index.d.ts"
25
+ "import": "./assignGingerly.js",
26
+ "types": "./types.d.ts"
27
27
  }
28
28
  },
29
- "main": "index.js",
29
+ "main": "assignGingerly.js",
30
30
  "scripts": {
31
31
  "serve": "node ./node_modules/spa-ssi/serve.js",
32
32
  "test": "playwright test",
package/index.d.ts DELETED
@@ -1,35 +0,0 @@
1
- /**
2
- * Interface for registry items that define dependency injection mappings
3
- */
4
- export interface IBaseRegistryItem<T = any> {
5
- spawn: { new (): T } | Promise<{ new (): T }>;
6
- map: { [key: string | symbol]: keyof T };
7
- }
8
-
9
- /**
10
- * Interface for the options passed to assignGingerly
11
- */
12
- export interface IAssignGingerlyOptions {
13
- registry?: typeof BaseRegistry | BaseRegistry;
14
- }
15
-
16
- /**
17
- * Base registry class for managing dependency injection
18
- */
19
- export declare class BaseRegistry {
20
- private items;
21
- push(items: IBaseRegistryItem | IBaseRegistryItem[]): void;
22
- getItems(): IBaseRegistryItem[];
23
- findBySymbol(symbol: symbol | string): IBaseRegistryItem | undefined;
24
- }
25
-
26
- /**
27
- * Main assignGingerly function
28
- */
29
- export declare function assignGingerly(
30
- target: any,
31
- source: Record<string | symbol, any>,
32
- options?: IAssignGingerlyOptions
33
- ): Promise<any>;
34
-
35
- export default assignGingerly;