Last active
November 24, 2021 14:32
-
-
Save cgiosy/1e47347d9a4e325c52a52410100496d9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const replaceSetMap = (object) => { | |
if (object) { | |
if (object.constructor === Set) return [...object]; | |
if (object.constructor === Map) return Object.fromEntries(object); | |
} | |
return object; | |
}; | |
const firstScan = ($, needle, { replacer = replaceSetMap, seen = new WeakMap() } = {}) => { | |
const found = []; | |
const _decycle = (object, path = "$") => { | |
if (replacer !== undefined) object = replacer(object); | |
let ctor; | |
if (object == null || !(ctor = object.constructor)) | |
return; | |
if (ctor === Number || ctor === String || ctor === Boolean || ctor === RegExp || ctor === Date || ctor === RegExp || typeof object !== "object") { | |
if(needle.constructor === Function ? needle(object) : object === needle) found.push({ path, value: object }); | |
return; | |
} | |
if (seen.has(object)) return; | |
seen.set(object, path); | |
if (ctor === Array) return object.map((value, key) => _decycle(value, `${path}[${key}]`)); | |
const result = { ...object }; | |
for (const key in result) _decycle(result[key], `${path}?.[${JSON.stringify(key)}]`); | |
return result; | |
}; | |
_decycle($); | |
return found; | |
}; | |
const nextScan = ($, found, needle) => found | |
.map(({ path, value }) => ({ path, prev: value, value: eval(path) })) | |
.filter(needle.constructor === Function ? needle : (x) => x.value === needle); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment