probejs-core
Version:
A powerful tool for traversing and investigating nested objects
70 lines • 2.03 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.detectCircular = detectCircular;
exports.isPlainObject = isPlainObject;
exports.deepClone = deepClone;
exports.memoize = memoize;
const errors_1 = require("./errors");
function detectCircular(obj, path = [], seen = new WeakSet()) {
if (typeof obj !== "object" || obj === null) {
return;
}
if (seen.has(obj)) {
throw new errors_1.CircularReferenceError(path.join("."));
}
seen.add(obj);
for (const [key, value] of Object.entries(obj)) {
if (typeof value === "object" && value !== null) {
detectCircular(value, [...path, key], seen);
}
}
}
function isPlainObject(obj) {
if (typeof obj !== "object" || obj === null)
return false;
let proto = Object.getPrototypeOf(obj);
if (proto === null)
return true;
let baseProto = proto;
while (Object.getPrototypeOf(baseProto) !== null) {
baseProto = Object.getPrototypeOf(baseProto);
}
return proto === baseProto;
}
function deepClone(obj) {
if (obj === null || typeof obj !== "object") {
return obj;
}
if (Array.isArray(obj)) {
return obj.map((item) => deepClone(item));
}
if (obj instanceof Date) {
return new Date(obj.getTime());
}
if (obj instanceof RegExp) {
return new RegExp(obj);
}
if (!isPlainObject(obj)) {
return obj;
}
const result = {};
for (const key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
result[key] = deepClone(obj[key]);
}
}
return result;
}
function memoize(fn, resolver) {
const cache = new Map();
return ((...args) => {
const key = resolver ? resolver(...args) : JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
});
}
//# sourceMappingURL=utils.js.map