object-deep-compare
Version:
A type-safe collection of comparison methods for objects and arrays in TypeScript/JavaScript
77 lines (76 loc) • 2.92 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.compareValuesWithDetailedDifferencesKeyFn = exports.compareValuesWithConflictsKeyFn = exports.comparePropertiesKeyFn = exports.Memoize = void 0;
/**
* Creates a memoized version of a function
* @param fn - Function to memoize
* @param keyFn - Optional custom function to generate cache keys
* @returns Memoized version of the function
*/
const Memoize = (fn, keyFn) => {
const cache = new Map();
return ((...args) => {
// Create a cache key from the arguments
const key = keyFn
? keyFn(...args)
: JSON.stringify(args);
// Check if result is in cache
if (cache.has(key)) {
return cache.get(key);
}
// Call the original function
const result = fn(...args);
// Store result in cache
cache.set(key, result);
return result;
});
};
exports.Memoize = Memoize;
/**
* Generate a cache key for CompareProperties
*/
const comparePropertiesKeyFn = (firstObject, secondObject) => {
return JSON.stringify([
Object.keys(firstObject).sort(),
Object.keys(secondObject).sort()
]);
};
exports.comparePropertiesKeyFn = comparePropertiesKeyFn;
/**
* Generate a cache key for CompareValuesWithConflicts
*/
const compareValuesWithConflictsKeyFn = (firstObject, secondObject, pathOfConflict = '', options = {}) => {
// Include path and options in the cache key
// Note: We stringify only specific options to avoid circular reference issues in the key generation itself
const safeOptions = {
strict: options.strict,
circularReferences: options.circularReferences
};
// For cache key, we use object IDs instead of full objects to avoid circular references
return JSON.stringify([
Object.keys(firstObject).sort().join(','),
Object.keys(secondObject).sort().join(','),
pathOfConflict,
safeOptions
]);
};
exports.compareValuesWithConflictsKeyFn = compareValuesWithConflictsKeyFn;
/**
* Generate a cache key for CompareValuesWithDetailedDifferences
*/
const compareValuesWithDetailedDifferencesKeyFn = (firstObject, secondObject, pathOfConflict = '', options = {}) => {
// Include path and options in the cache key
// Note: We stringify only specific options to avoid circular reference issues in the key generation itself
const safeOptions = {
strict: options.strict,
circularReferences: options.circularReferences
};
// For cache key, we use object IDs instead of full objects to avoid circular references
return JSON.stringify([
Object.keys(firstObject).sort().join(','),
Object.keys(secondObject).sort().join(','),
pathOfConflict,
safeOptions
]);
};
exports.compareValuesWithDetailedDifferencesKeyFn = compareValuesWithDetailedDifferencesKeyFn;