-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
533 lines (436 loc) · 15.4 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
let __DEV__ = process.env.NODE_ENV === 'development' || (typeof window !== 'undefined') && localStorage.getItem('debug') === 'changeless';
const isFunction = value => typeof value === 'function';
const isUndefined = value => value === undefined;
const isString = value => typeof value === 'string';
const {isArray} = Array;
const isArrayLike = value => length in value;
const isObject = value => typeof value === 'object' && value !== null;
const sliceArguments = (args, start, end = args.length) => {
var ret = Array(end - start);
for (var i = start, j = 0; i < end; i++ , j++) ret[j] = args[i];
return ret;
}
const maybeExecute = (maybeFn, arg) =>
isFunction(maybeFn) ? maybeFn(arg) : maybeFn;
const pathSplitter = '___';
const pathToArray = (path, splitter = pathSplitter) => isString(path) ? path.split(splitter) : path;
// Symbols
const cacheKey = '__changeless__cache__';
const clonerKey = '__changeless__cloner__';
const didChange = '__changeless__did__change__';
const dummy = {};
// add non-enumerable properties to objects
const addPropertyTo = (target, methodName, value) => Object.defineProperty(
target, methodName, {
enumerable: false,
configurable: true,
writable: true,
value: value
});
const hasCache = obj => Boolean(obj[cacheKey]);
// exporting for tests
const fns = {
// generates a structured clone function for a given object
createCloner(obj) {
let objDef = '{';
fns.forEachInObject(obj, (val, key) =>
objDef += `'${key}': obj['${key}'],`);
objDef += '}';
return Function('obj', 'return ' + objDef);
},
simpleCloner(obj) {
let target = {};
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
target[i] = obj[i];
}
}
return target;
},
// clones object using the generated cloner.
// saves that cloner as a property the object and clone
cloneObject(obj) {
let cloner = obj[clonerKey];
if (!cloner) {
cloner = fns.createCloner(obj);
addPropertyTo(obj, clonerKey, cloner);
}
const clone = cloner(obj);
addPropertyTo(clone, clonerKey, cloner);
return clone;
},
cloneArray(arr) {
var res = Array(arr.length);
for (var i = 0; i < arr.length; i++) res[i] = arr[i];
return res;
},
cloneShallow(value) {
return isArray(value) ? fns.cloneArray(value) : fns.cloneObject(value);
},
forEachInArrayRight(arr, cb) {
for (let i = arr.length - 1; i >= 0; i--) {
if (cb(arr[i], i, arr) === false) return;
}
},
forEachInArray(arr, cb) {
for (let i = 0, len = arr.length; i < len; i++) {
if (cb(arr[i], i, arr) === false) return;
}
},
forEachInObject(obj, cb) {
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
if (cb(obj[key], key, obj) === false) return;
}
}
},
iterate(value) {
return isArrayLike(value) ? fns.forEachInArray(value) : fns.forEachInObject(value);
},
// define a cache for changes. changes won't happen until applyMutation is called
stageMutations(obj) {
const cache = isArray(obj) ? [] : {};
addPropertyTo(obj, cacheKey, cache);
return obj;
},
// apply stages mutations
applyMutations(object, changes) {
const cache = object[cacheKey];
const changesToApply = changes || fns.getMergerChanges(cache);
const cloned = fns.cloneShallow(object);
fns.traverse(cloned, (val, key, path, obj, isObj) => {
if (changesToApply.hasOwnProperty(path)) {
// pass over objects in the path, cloning all of their properties.
// if it's the value we want to set, set it.
obj[key] = isObj
? fns.cloneShallow(obj[key])
: changesToApply[path];
changesToApply[path] = didChange;
} else {
// short-cut, stop traversing path if it isn't in the changes.
return false;
}
});
// other changes to new paths on the object.
fns.forEachInObject(changesToApply, (val, path) => {
if (val !== didChange) {
fns.walkPathInObject(cloned, path, fns.getPathUpdater(val, true));
}
});
return cloned;
},
/**
* @name getMergerChanges
* @returns {object} an object with all the changes needed for the merge,
* as [path, value] pairs.
*/
getMergerChanges() {
const contextPath = arguments[0];
const hasPath = isString(contextPath);
const arrayPath = pathToArray(contextPath);
const changes = {};
let args = arguments;
if (hasPath) {
args = sliceArguments(args, 1);
let path = '';
fns.forEachInArray(arrayPath, (val) => {
path = path ? `${path}${pathSplitter}${val}` : val;
changes[path] = dummy;
});
}
const doTraverse = obj => fns.traverse(
obj,
(value, key, path) => {
if (hasPath) {
path = `${contextPath}${pathSplitter}${path}`;
}
if (!changes.hasOwnProperty(path)) {
changes[path] = value;
}
}
);
// collect changes
fns.forEachInArrayRight(args, doTraverse);
return changes;
},
/**
* @name mutateMerge
* merges sources into target, mutates the merge target.
* @param {object|array} target merge target.
* @params {object|array} sources merge sources.
* @returns {object|array} merged target
*/
mutateMerge() {
const args = sliceArguments(arguments, 1);
const changes = fns.getMergerChanges.apply(null, args);
const target = arguments[0];
// apply changes
fns.forEachInObject(changes, (val, path) =>
fns.walkPathInObject(target, path, fns.getPathUpdater(val, true)));
return target;
},
// _traverse(obj, cb, context = '') {
// fns.forEachInObject(obj, (val, key) => {
// const path = context ? context + pathSplitter + key : key;
// const isObj = isObject(val);
// const shouldContinue = cb(val, key, path, obj, isObj);
// if (isObj && shouldContinue !== false) {
// // obj[key] instead of val to take changes as we traverse into account
// fns._traverse(obj[key], cb, path);
// }
// });
// },
/**
* @name traverse
* traverse an object with a callback.
* @param {object|array} obj object to traverse.
* @param {function} cb callback for each node. will be called for each node,
* with the value and current path to the node from the root object, as well
* as a third value to be true if the node is an object.
* @returns {undefined} N/A
*/
// TODO improve perf
traverse(obj, cb, context = '') {
let keys = [],
objs = [],
paths = [],
len = 0;
for (let k in obj) {
keys[len] = k;
objs[len] = obj;
paths[len] = context;
len++;
}
for (let i = 0; i < len; i++) {
const key = keys[i];
const obj = objs[i];
const val = obj[key];
const context = paths[i];
const path = context ? context + pathSplitter + key : key;
const isObj = isObject(val);
const shouldContinue = cb(val, key, path, obj, isObj);
if (isObj && shouldContinue !== false) {
const keyObj = obj[key];
for (let k in keyObj) {
keys[len] = k;
objs[len] = keyObj;
paths[len] = path;
len++;
}
}
}
},
/**
* @name walkPathInObject
* updates an object path (or a cache).
* @param {object} obj
* @param {string|array} path
* @param {function} cb
* @param {object} cache optionally use a cache to store the changes
* instead of the object.
* @returns {undefined} N/A
*/
walkPathInObject(obj, path, cb, cache) {
const withCache = isObject(cache);
const arrayPath = pathToArray(path);
let curObj = obj;
let curCache = cache;
fns.forEachInArray(arrayPath, (p, i, arr) => {
const context = curCache || curObj;
if (i === arr.length - 1) {
cb(context, p, context[p]);
} else {
cb(context, p);
curObj = curObj[p];
if (withCache) {
curCache = curCache[p];
}
}
});
},
// deep freeze an object, convenient for development.
freeze(obj) {
Object.freeze(obj);
fns.traverse(obj, (val, path, isObj) =>
isObj && Object.freeze(path));
return obj;
},
getPathUpdater(fn, dontClone) {
const toClone = [];
return function (context, key, currentValue) {
switch (arguments.length) {
// inner object
case 2:
let c = context[key];
if (isUndefined(c) || !isObject(c)) {
context[key] = {};
} else if (!dontClone) {
toClone.push([context, key]);
}
break;
// value to set
case 3:
const value = maybeExecute(fn, currentValue);
// only set if necessary, ignore NaN
if (context[key] !== value && value === value) {
// if we passed over objects, clone them
const last = toClone.length - 1;
fns.forEachInArray(toClone, ([_context, _key], i) => {
_context[_key] = fns.cloneShallow(_context[_key]);
// update the property on the *cloned* context
if (i === last) {
context = _context[_key];
}
});
// set the value.
// this should be done here and only here, in the whole module.
if (context[clonerKey] && !(key in context)) {
if (__DEV__) {
let formatted = '<object>';
try {
const stringified = JSON.stringify(context);
formatted = stringified.length > 20 ? stringified.slice(0, 20) + '... }' : stringified;
} catch (e) {
}
console.warn(`Setting a new property <${key}> on ${formatted}. This causes de-optimisation in object cloning`);
}
addPropertyTo(context, clonerKey, fns.simpleCloner);
}
context[key] = value;
}
break;
}
};
},
get(obj, path) {
const arrayPath = pathToArray(path);
fns.forEachInArray(arrayPath, p => {
if (!isObject(obj)) {
obj = undefined;
return false;
}
obj = obj[p];
});
return obj;
}
};
const update = (obj, path, fn) => {
if (isChangeless(obj)) {
return obj.update(path, fn);
}
const cache = obj[cacheKey];
const cloned = cache ? obj : fns.cloneShallow(obj);
const updater = fns.getPathUpdater(fn, Boolean(cache));
fns.walkPathInObject(
cloned,
path,
updater,
cache
);
return cloned;
};
const withMutations = function (obj, fn) {
if (isChangeless(obj)) {
return obj.withMutations(fn);
}
const actions = this && this.__actions__;
const changeless = new Changeless(obj, actions);
const mutated = fn(changeless);
return hasCache(obj)
? mutated
: changeless.value();
};
const merge = function () {
const obj = arguments[0];
if (isChangeless(obj)) {
return obj.merge.apply(obj, args);
}
let cache = obj[cacheKey];
const args = sliceArguments(arguments, 1);
const path = args[0];
const hasPath = isString(path);
if (hasPath) {
args.unshift();
}
if (cache) {
if (hasPath) {
fns.walkPathInObject(cache, path, fns.getPathUpdater({}, true));
cache = fns.get(cache, path);
}
args.unshift(cache);
fns.mutateMerge.apply(null, args);
} else {
const changes = fns.getMergerChanges.apply(null, args);
return fns.applyMutations(obj, changes, !hasPath);
}
};
const set = update;
const publicAPI = { merge, update, set, withMutations };
const isChangeless = obj => obj instanceof Changeless;
/**
* Creates a new changeless instance. can be called as a regular function.
* Similar to lodash wrappers, batches operations and performs them lazily,
* when Changeless#value is called.
* All API methods can be called as methods of this class' instances, without
* the object as the first argument.
* e.g. set(someObject, 'a.b', 42) becomes wrappedObject.set('a.b', 42).
* @class
* @param {object|array} wrapped object or array to wrap for batched mutations.
* @param {array} actions existing actions (used internally).
*/
const Changeless = function Changeless(wrapped, actions) {
if (isChangeless(wrapped)) {
return wrapped;
}
// "call constructor"
if (!isChangeless(this)) {
return new Changeless(wrapped, actions);
}
this.__wrapped__ = wrapped;
this.__actions__ = actions || [];
};
/**
* performs the actions on the wrapped object, and returns the object/array.
* @method
* @name value
* @returns {object|array}
*/
Changeless.prototype.value = function () {
let wrapped = this.__wrapped__;
const actions = this.__actions__;
// since the instance's __actions__ is mutated as we go through the actions,
// save a copy and restore it when done, so we can call `value` again.
const savedActions = fns.cloneArray(actions);
fns.stageMutations(wrapped);
for (let i = 0, len = actions.length; i < len; i++ , len = actions.length) {
actions[i](wrapped);
}
this.__actions__ = savedActions;
return fns.applyMutations(wrapped);
};
/**
* Plants another wrapped object/array in the wrapper.
* @method
* @name plant
* @param {object|array} wrapped
*/
Changeless.prototype.plant = function (wrapped) {
this.__wrapped__ = wrapped;
return this;
};
fns.forEachInObject(publicAPI, (val, key) => {
Changeless[key] = val;
Changeless.prototype[key] = function () {
this.__actions__.push(obj => {
const args = [obj, ...arguments];
return val.apply(this, args);
});
return this;
};
});
exports.fns = fns;
exports.default = Changeless;
exports.update = update;
exports.withMutations = withMutations;
exports.merge = merge;
exports.set = set;