Skip to content

Instantly share code, notes, and snippets.

@cgiosy
Last active November 24, 2021 14:32
Show Gist options
  • Save cgiosy/1e47347d9a4e325c52a52410100496d9 to your computer and use it in GitHub Desktop.
Save cgiosy/1e47347d9a4e325c52a52410100496d9 to your computer and use it in GitHub Desktop.
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