forked from dexie/Dexie.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
280 lines (254 loc) · 9.01 KB
/
utils.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
/*
* Dexie.js - a minimalistic wrapper for IndexedDB
* ===============================================
*
* By David Fahlander, david.fahlander@gmail.com
*
* Version {version}, {date}
* www.dexie.com
* Apache License Version 2.0, January 2004, http://www.apache.org/licenses/
*/
export var keys = Object.keys;
export var isArray = Array.isArray;
export var _global =
typeof self !== 'undefined' ? self :
typeof window !== 'undefined' ? window :
global;
export function extend(obj, extension) {
if (typeof extension !== 'object') return obj;
keys(extension).forEach(function (key) {
obj[key] = extension[key];
});
return obj;
}
export const getProto = Object.getPrototypeOf;
export const _hasOwn = {}.hasOwnProperty;
export function hasOwn(obj, prop) {
return _hasOwn.call(obj, prop);
}
export function props (proto, extension) {
if (typeof extension === 'function') extension = extension(getProto(proto));
keys(extension).forEach(key => {
setProp(proto, key, extension[key]);
});
}
export const defineProperty = Object.defineProperty;
export function setProp(obj, prop, functionOrGetSet, options) {
defineProperty(obj, prop, extend(functionOrGetSet && hasOwn(functionOrGetSet, "get") && typeof functionOrGetSet.get === 'function' ?
{get: functionOrGetSet.get, set: functionOrGetSet.set, configurable: true} :
{value: functionOrGetSet, configurable: true, writable: true}, options));
}
export function derive(Child) {
return {
from: function (Parent) {
Child.prototype = Object.create(Parent.prototype);
setProp(Child.prototype, "constructor", Child);
return {
extend: props.bind(null, Child.prototype)
};
}
};
}
export const getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
export function getPropertyDescriptor(obj, prop) {
var pd = getOwnPropertyDescriptor(obj, prop),
proto;
return pd || (proto = getProto(obj)) && getPropertyDescriptor (proto, prop);
}
var _slice = [].slice;
export function slice(args, start, end) {
return _slice.call(args, start, end);
}
export function override(origFunc, overridedFactory) {
return overridedFactory(origFunc);
}
export function doFakeAutoComplete(fn) {
var to = setTimeout(fn, 1000);
clearTimeout(to);
}
export function assert (b) {
if (!b) throw new Error("Assertion Failed");
}
export function asap(fn) {
if (_global.setImmediate) setImmediate(fn); else setTimeout(fn, 0);
}
export function getUniqueArray(a) {
return a.filter((value, index, self) => self.indexOf(value) === index);
}
/** Generate an object (hash map) based on given array.
* @param extractor Function taking an array item and its index and returning an array of 2 items ([key, value]) to
* instert on the resulting object for each item in the array. If this function returns a falsy value, the
* current item wont affect the resulting object.
*/
export function arrayToObject (array, extractor) {
return array.reduce((result, item, i) => {
var nameAndValue = extractor(item, i);
if (nameAndValue) result[nameAndValue[0]] = nameAndValue[1];
return result;
}, {});
}
export function trycatcher(fn, reject) {
return function () {
try {
fn.apply(this, arguments);
} catch (e) {
reject(e);
}
};
}
export function tryCatch(fn, onerror, args) {
try {
fn.apply(null, args);
} catch (ex) {
onerror && onerror(ex);
}
}
export function getByKeyPath(obj, keyPath) {
// http://www.w3.org/TR/IndexedDB/#steps-for-extracting-a-key-from-a-value-using-a-key-path
if (hasOwn(obj, keyPath)) return obj[keyPath]; // This line is moved from last to first for optimization purpose.
if (!keyPath) return obj;
if (typeof keyPath !== 'string') {
var rv = [];
for (var i = 0, l = keyPath.length; i < l; ++i) {
var val = getByKeyPath(obj, keyPath[i]);
rv.push(val);
}
return rv;
}
var period = keyPath.indexOf('.');
if (period !== -1) {
var innerObj = obj[keyPath.substr(0, period)];
return innerObj === undefined ? undefined : getByKeyPath(innerObj, keyPath.substr(period + 1));
}
return undefined;
}
export function setByKeyPath(obj, keyPath, value) {
if (!obj || keyPath === undefined) return;
if ('isFrozen' in Object && Object.isFrozen(obj)) return;
if (typeof keyPath !== 'string' && 'length' in keyPath) {
assert(typeof value !== 'string' && 'length' in value);
for (var i = 0, l = keyPath.length; i < l; ++i) {
setByKeyPath(obj, keyPath[i], value[i]);
}
} else {
var period = keyPath.indexOf('.');
if (period !== -1) {
var currentKeyPath = keyPath.substr(0, period);
var remainingKeyPath = keyPath.substr(period + 1);
if (remainingKeyPath === "")
if (value === undefined) delete obj[currentKeyPath]; else obj[currentKeyPath] = value;
else {
var innerObj = obj[currentKeyPath];
if (!innerObj) innerObj = (obj[currentKeyPath] = {});
setByKeyPath(innerObj, remainingKeyPath, value);
}
} else {
if (value === undefined) delete obj[keyPath]; else obj[keyPath] = value;
}
}
}
export function delByKeyPath(obj, keyPath) {
if (typeof keyPath === 'string')
setByKeyPath(obj, keyPath, undefined);
else if ('length' in keyPath)
[].map.call(keyPath, function(kp) {
setByKeyPath(obj, kp, undefined);
});
}
export function shallowClone(obj) {
var rv = {};
for (var m in obj) {
if (hasOwn(obj, m)) rv[m] = obj[m];
}
return rv;
}
export function deepClone(any) {
if (!any || typeof any !== 'object') return any;
var rv;
if (isArray(any)) {
rv = [];
for (var i = 0, l = any.length; i < l; ++i) {
rv.push(deepClone(any[i]));
}
} else if (any instanceof Date) {
rv = new Date();
rv.setTime(any.getTime());
} else {
rv = any.constructor ? Object.create(any.constructor.prototype) : {};
for (var prop in any) {
if (hasOwn(any, prop)) {
rv[prop] = deepClone(any[prop]);
}
}
}
return rv;
}
export function getObjectDiff(a, b, rv, prfx) {
// Compares objects a and b and produces a diff object.
rv = rv || {};
prfx = prfx || '';
keys(a).forEach(prop => {
if (!hasOwn(b, prop))
rv[prfx+prop] = undefined; // Property removed
else {
var ap = a[prop],
bp = b[prop];
if (typeof ap === 'object' && typeof bp === 'object' &&
ap && bp &&
ap.constructor === bp.constructor)
// Same type of object but its properties may have changed
getObjectDiff (ap, bp, rv, prfx + prop + ".");
else if (ap !== bp)
rv[prfx + prop] = b[prop];// Primitive value changed
}
});
keys(b).forEach(prop => {
if (!hasOwn(a, prop)) {
rv[prfx+prop] = b[prop]; // Property added
}
});
return rv;
}
// If first argument is iterable or array-like, return it as an array
export const iteratorSymbol = typeof Symbol !== 'undefined' && Symbol.iterator;
export const getIteratorOf = iteratorSymbol ? function(x) {
var i;
return x != null && (i = x[iteratorSymbol]) && i.apply(x);
} : function () { return null; };
export const NO_CHAR_ARRAY = {};
// Takes one or several arguments and returns an array based on the following criteras:
// * If several arguments provided, return arguments converted to an array in a way that
// still allows javascript engine to optimize the code.
// * If single argument is an array, return a clone of it.
// * If this-pointer equals NO_CHAR_ARRAY, don't accept strings as valid iterables as a special
// case to the two bullets below.
// * If single argument is an iterable, convert it to an array and return the resulting array.
// * If single argument is array-like (has length of type number), convert it to an array.
export function getArrayOf (arrayLike) {
var i, a, x, it;
if (arguments.length === 1) {
if (isArray(arrayLike)) return arrayLike.slice();
if (this === NO_CHAR_ARRAY && typeof arrayLike === 'string') return [arrayLike];
if ((it = getIteratorOf(arrayLike))) {
a = [];
while ((x = it.next()), !x.done) a.push(x.value);
return a;
}
if (arrayLike == null) return [arrayLike];
i = arrayLike.length;
if (typeof i === 'number') {
a = new Array(i);
while (i--) a[i] = arrayLike[i];
return a;
}
return [arrayLike];
}
i = arguments.length;
a = new Array(i);
while (i--) a[i] = arguments[i];
return a;
}
const concat = [].concat;
export function flatten (a) {
return concat.apply([], a);
}