MCPcopy Create free account
hub / github.com/violentmonkey/violentmonkey / mapEntry

Function mapEntry

src/common/object.js:62–186  ·  view source on GitHub ↗
(fnValue, fnKey, thisObj)

Source from the content-addressed store, hash-verified

60 * @return {Object}
61 */
62export 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) => {})
74export function forEachEntry(func, thisObj) {
75 if (this) Object.entries(this).forEach(func, thisObj);
76}
77
78// invoked as obj::forEachKey(key => {}, i, allKeys)
79export function forEachKey(func, thisObj) {
80 if (this) Object.keys(this).forEach(func, thisObj);
81}
82
83// invoked as obj::forEachValue(value => {}, i, allValues)
84export function forEachValue(func, thisObj) {
85 if (this) Object.values(this).forEach(func, thisObj);
86}
87
88export 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
97export 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 */
114export 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);

Callers 3

getMultiMethod · 0.90
setMethod · 0.90
prepareScriptFunction · 0.90

Calls 1

mapMethod · 0.80

Tested by

no test coverage detected