import { ObjectType, ObjectKeyType } from '../types/PrimitiveType'; export default class ObjectHelper { static reduce( obj: O, callback: (accumulator: A, value: V, key: keyof O, obj: O) => A, initialValue: A, ): A { let res = initialValue; for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } res = callback(res, obj[key], key, obj); } return res; } // Obj => map over props static map( obj: O, callback: (value: V, key: keyof O, obj: O) => R, ): Record { const newObj = {} as Record; for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } newObj[key] = callback(obj[key], key, obj); } return newObj; } static filter( obj: O, callback: (value: V, key: keyof O, obj: O) => boolean, ): Partial> { const newObj = {} as Partial>; for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } if (callback(obj[key], key, obj)) { newObj[key] = obj[key]; } } return newObj; } static forEach( obj: O, callback: (value: V, key: keyof O, obj: O) => void, ): void { for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } callback(obj[key], key, obj); } } static some( obj: O, callback: (value: V, key: keyof O, obj: O) => boolean, ): boolean { for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } if (callback(obj[key], key, obj)) { return true; } } return false; } static every( obj: O, callback: (value: V, key: keyof O, obj: O) => boolean, ): boolean { for (const key in obj) { if (!obj.hasOwnProperty(key)) { continue; } if (!callback(obj[key], key, obj)) { return false; } } return true; } /** * Retuns list of keys for keys with different values */ static diffKeysByValue(obj1: T, obj2: T, ignoreProps: ObjectKeyType[] = []): ObjectKeyType[] { const ignorePropsSet = new Set(ignoreProps); const changedProps: ObjectKeyType[] = []; this.forEach(obj1, (value, key) => { if (ignorePropsSet.has(key)) { return; } if (!obj2.hasOwnProperty(key) || obj2[key] !== value) { changedProps.push(key); } }); this.forEach(obj2, (_, key) => { if (ignorePropsSet.has(key)) { return; } if (!obj1.hasOwnProperty(key)) { changedProps.push(key); } }); return changedProps; } }