datum-merge
Version:
Simplified diff and merging for deeply nested objects
95 lines (94 loc) • 3 kB
JavaScript
import { cloneDeep, get } from "lodash-es";
import equal from 'fast-deep-equal';
export function getObjectKeys(obj, excludeKeys, includeKeys) {
if (!obj) {
return [];
}
let sourceKeys = Object.keys(obj);
if (includeKeys && !!includeKeys.length) {
includeKeys.filter((k) => !sourceKeys.includes(k))
.forEach((k) => sourceKeys.push(k));
}
if (excludeKeys && !!excludeKeys.length) {
sourceKeys = sourceKeys.filter((k) => !excludeKeys.includes(k));
}
return sourceKeys;
}
;
export function isPlainObject(value) {
if (typeof value !== 'object' || value === null)
return false;
const proto = Object.getPrototypeOf(value);
return proto === null || proto === Object.prototype;
}
export function createValueKeys(keys, value) {
return Object.fromEntries(keys.map((k) => [k, value]));
}
export function shallowEquals(lhs, rhs) {
return lhs === rhs;
}
export function deepEquals(lhs, rhs) {
if (lhs === rhs)
return true;
return equal(lhs, rhs);
}
export function deepEqualsPath(lhs, rhs, atPath) {
return equal(get(lhs, atPath), get(rhs, atPath));
}
export function deepClone(val) {
return cloneDeep(val);
}
export function areArraysEqual(arr1, arr2) {
if (arr1 == null && arr2 == null)
return true;
if (arr1 == null || arr2 == null)
return false;
if (arr1.length !== arr2.length)
return false;
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
export function fastGlobMatch(glob, text) {
if (!glob.includes("*"))
return text === glob;
if (glob === "*")
return typeof text === "string";
const globParts = glob.split(/\*+/g, -1);
const partsLen = globParts.length;
if (partsLen === 0)
return !text;
const prefix = globParts[0];
if (partsLen === 1)
return text === prefix;
if (!text.startsWith(prefix))
return false;
let textIdx = prefix.length;
for (let i = 1; i < partsLen - 1; i++) {
const nextIdx = text.indexOf(globParts[i], textIdx);
if (nextIdx < 0) {
return false;
}
textIdx = nextIdx + globParts[i].length;
continue;
}
const suffix = globParts[partsLen - 1];
if (textIdx > text.length - suffix.length)
return false;
if (!text.endsWith(suffix))
return false;
return true;
}
export function getGlobKeys(obj, inclGlobs = ["*"], exclGlobs) {
return Object.keys(obj)
.filter((k) => !inclGlobs || inclGlobs.some((g) => fastGlobMatch(g, k)))
.filter((k) => !(exclGlobs === null || exclGlobs === void 0 ? void 0 : exclGlobs.length) || !exclGlobs.some((g) => fastGlobMatch(g, k)));
}
export function selectObjKeys(obj, inclKeys) {
inclKeys = inclKeys || getObjectKeys(obj);
return Object.fromEntries(Object.entries(obj)
.filter(([k, _]) => inclKeys.includes(k)));
}