|
| 1 | +/** |
| 2 | + * Get the first item that pass the test |
| 3 | + * by second argument function |
| 4 | + * |
| 5 | + * @param {Array} list |
| 6 | + * @param {Function} f |
| 7 | + * @return {*} |
| 8 | + */ |
| 9 | +function find (list, f) { |
| 10 | + return list.filter(f)[0] |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Deep copy the given object considering circular structure. |
| 15 | + * This function caches all nested objects and its copies. |
| 16 | + * If it detects circular structure, use cached copy to avoid infinite loop. |
| 17 | + * |
| 18 | + * @param {*} obj |
| 19 | + * @param {Array<Object>} cache |
| 20 | + * @return {*} |
| 21 | + */ |
| 22 | +export function deepCopy (obj, cache = []) { |
| 23 | + // just return if obj is immutable value |
| 24 | + if (obj === null || typeof obj !== 'object') { |
| 25 | + return obj |
| 26 | + } |
| 27 | + |
| 28 | + // if obj is hit, it is in circular structure |
| 29 | + const hit = find(cache, c => c.original === obj) |
| 30 | + if (hit) { |
| 31 | + return hit.copy |
| 32 | + } |
| 33 | + |
| 34 | + const copy = Array.isArray(obj) ? [] : {} |
| 35 | + // put the copy into cache at first |
| 36 | + // because we want to refer it in recursive deepCopy |
| 37 | + cache.push({ |
| 38 | + original: obj, |
| 39 | + copy |
| 40 | + }) |
| 41 | + |
| 42 | + Object.keys(obj).forEach(key => { |
| 43 | + copy[key] = deepCopy(obj[key], cache) |
| 44 | + }) |
| 45 | + |
| 46 | + return copy |
| 47 | +} |
| 48 | + |
| 49 | +export function isObject (obj) { |
| 50 | + return obj !== null && typeof obj === 'object' |
| 51 | +} |
| 52 | + |
| 53 | +export function isPromise (val) { |
| 54 | + return val && typeof val.then === 'function' |
| 55 | +} |
| 56 | + |
| 57 | +export function assert (condition, msg) { |
| 58 | + if (!condition) throw new Error(`[vuex] ${msg}`) |
| 59 | +} |
0 commit comments