Skip to content

Instantly share code, notes, and snippets.

@aprilandjan
Created April 2, 2019 11:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aprilandjan/7beba8a5c60882efd603b742f5a234a5 to your computer and use it in GitHub Desktop.
Save aprilandjan/7beba8a5c60882efd603b742f5a234a5 to your computer and use it in GitHub Desktop.
hand-made, lightweight utility functions to do value operations.
/**
* test if the target is an object(array included)
*/
export function isObject(obj: any): boolean {
return obj !== null && typeof obj === 'object';
}
/** simple deep equal */
export function isEqual(a: any, b: any): boolean {
if (isObject(a) && isObject(b)) {
const aKeys = Object.keys(a);
const bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
} else {
return aKeys.every((key) => isEqual(a[key], b[key]));
}
} else {
return a === b;
}
}
/** simple deep merge */
export function merge<T>(val: T, data: any): T {
let merged: any = val;
if (isObject(val)) {
// ignore simple val into object
if (isObject(data)) {
Object.keys(data).forEach((key, index) => {
const src = (val as any)[key];
const dst = data[key];
(val as any)[key] = merge(src, dst);
});
}
} else {
// if src is not object, just replace it
merged = data;
}
return merged as T;
}
/** simple deep clone, without retain ref */
export function cloneDeep<T>(val: T): T {
let cloned: any;
if (Array.isArray(val)) {
cloned = [];
(val as any).forEach((item: any, idx: number) => {
cloned[idx] = cloneDeep(item);
});
} else if (isObject(val)) {
cloned = {};
Object.keys(val).forEach((key) => {
cloned[key] = cloneDeep((val as any)[key]);
});
} else {
cloned = val;
}
return cloned as T;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment