diff --git a/packages/object-util/README.md b/packages/object-util/README.md index 80cdd23..1bf6b2e 100644 --- a/packages/object-util/README.md +++ b/packages/object-util/README.md @@ -53,6 +53,10 @@ objectSize(object) // like Array.sort it sort and return an ordered object objectSort(object, /*optionnal*/ (key1, key2) => key1 - key2) +// You can also sort by keys +// items not set in the array won't have their order changed and will be after the sorted ones +objectSort(object, ['key2', 'key1']) // => {key2: value, key1: value, key3: value} + // deeply clone an object cloneObject(object) diff --git a/packages/object-util/__tests__/index.test.ts b/packages/object-util/__tests__/index.test.ts index 27fc12b..1838b49 100644 --- a/packages/object-util/__tests__/index.test.ts +++ b/packages/object-util/__tests__/index.test.ts @@ -52,7 +52,7 @@ describe('Object Keys Tests', () => { }) }) -describe('Object Sort Tests', () => { +describe('Object Size Tests', () => { it('shoud return length of the object', () => { const obj = { index0: true, @@ -82,6 +82,20 @@ describe('Object sort Tests', () => { b: 'first' }) }) + it('should sort by the specified key', () => { + const obj = { + b: 'first', + a: 'second', + c: 'zero', + d: 'fourth' + } + expect(objectSort(obj, ['c', 'a'])).toEqual({ + c: 'zero', + a: 'second', + b: 'first', + d: 'fourth' + }) + }) }) describe('Object Clone Tests', () => { diff --git a/packages/object-util/src/ObjectUtil.ts b/packages/object-util/src/ObjectUtil.ts index 36c25d5..52db999 100644 --- a/packages/object-util/src/ObjectUtil.ts +++ b/packages/object-util/src/ObjectUtil.ts @@ -62,12 +62,18 @@ export function objectSize(obj: Record): number { * @param obj the object to sort * @param fn (Optionnal) the function to run to sort */ -export function objectSort>( - obj: Record, - fn?: (a: string, b: string) => number +export function objectSort = Record>( + obj: T, + fn?: Array | ((a: keyof T, b: keyof T) => number) ): T { const ordered: any = {} - for (const key of objectKeys(obj).sort(fn)) { + let sortedKeys: Array = [] + if (Array.isArray(fn)) { + sortedKeys = fn.concat(objectKeys(obj).filter((k) => !fn.includes(k))) + } else { + sortedKeys = objectKeys(obj).sort(fn) + } + for (const key of sortedKeys) { ordered[key] = obj[key] } return ordered