(fnValue, fnKey, thisObj)
| 60 | * @return {Object} |
| 61 | */ |
| 62 | export function mapEntry(fnValue, fnKey, thisObj) { |
| 63 | const res = {}; |
| 64 | for (let key of Object.keys(this)) { |
| 65 | const val = this[key]; |
| 66 | if (!fnKey || (key = thisObj::fnKey(key, val, this))) { |
| 67 | res[key] = fnValue ? thisObj::fnValue(val, key, this) : val; |
| 68 | } |
| 69 | } |
| 70 | return res; |
| 71 | } |
| 72 | |
| 73 | // invoked as obj::forEachEntry(([key, value], i, allEntries) => {}) |
| 74 | export function forEachEntry(func, thisObj) { |
| 75 | if (this) Object.entries(this).forEach(func, thisObj); |
| 76 | } |
| 77 | |
| 78 | // invoked as obj::forEachKey(key => {}, i, allKeys) |
| 79 | export function forEachKey(func, thisObj) { |
| 80 | if (this) Object.keys(this).forEach(func, thisObj); |
| 81 | } |
| 82 | |
| 83 | // invoked as obj::forEachValue(value => {}, i, allValues) |
| 84 | export function forEachValue(func, thisObj) { |
| 85 | if (this) Object.values(this).forEach(func, thisObj); |
| 86 | } |
| 87 | |
| 88 | export function deepCopy(src) { |
| 89 | if (!src || typeof src !== 'object') return src; |
| 90 | // Using a literal [] instead of `src.map(deepCopy)` to avoid src `window` leaking. |
| 91 | // Using `concat` instead of `for` loop to preserve holes in the array. |
| 92 | if (Array.isArray(src)) return [].concat(src).map(deepCopy); |
| 93 | return src::mapEntry(deepCopy); |
| 94 | } |
| 95 | |
| 96 | // Simplified deep equality checker |
| 97 | export function deepEqual(a, b) { |
| 98 | let res; |
| 99 | if (!a || !b || typeof a !== typeof b || typeof a !== 'object') { |
| 100 | res = a === b; |
| 101 | } else if (Array.isArray(a)) { |
| 102 | res = a.length === b.length && a.every((item, i) => deepEqual(item, b[i])); |
| 103 | } else { |
| 104 | const keysA = Object.keys(a); |
| 105 | /* Not checking hasOwnProperty because 1) we only use own properties and |
| 106 | * 2) this can be slow for a large value storage that has thousands of keys */ |
| 107 | res = keysA.length === Object.keys(b).length |
| 108 | && keysA.every(key => deepEqual(a[key], b[key])); |
| 109 | } |
| 110 | return res; |
| 111 | } |
| 112 | |
| 113 | /** @return {?} `undefined` if equal */ |
| 114 | export function deepCopyDiff(src, sample) { |
| 115 | if (src === sample) return; |
| 116 | if (!src || typeof src !== 'object') return src; |
| 117 | if (!sample || typeof sample !== 'object') return deepCopy(src); |
| 118 | deepDiff = false; |
| 119 | src = (Array.isArray(src) ? deepCopyDiffArrays : deepCopyDiffObjects)(src, sample); |
no test coverage detected