Skip to content

Commit 99de469

Browse files
author
Ovidiu Barabula
committed
feat(util): add utility function for object key sorting
1 parent 7f3db59 commit 99de469

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/util/utility-functions.spec.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
required,
2121
retry,
2222
sleep,
23+
sortObjectKeys,
2324
} from './utility-functions';
2425

2526
describe('Utility Functions', () => {
@@ -526,4 +527,24 @@ describe('Utility Functions', () => {
526527
expect(getPrefix('foo')).to.equal('foo');
527528
});
528529
});
530+
531+
532+
describe('sortObjectKeys()', () => {
533+
it('returns the sorted object', () => {
534+
expect(Object.keys(sortObjectKeys({ c: 3, b: 2, a: 1 })))
535+
.to.deep.equal(Object.keys({ a: 1, b: 2, c: 3 }));
536+
});
537+
538+
539+
it('returns sorted object if already sorted', () => {
540+
expect(Object.keys(sortObjectKeys({ a: 1, b: 2, c: 3 })))
541+
.to.deep.equal(Object.keys({ a: 1, b: 2, c: 3 }));
542+
});
543+
544+
545+
it('returns empty object, if empty object is passed in', () => {
546+
expect(sortObjectKeys({}))
547+
.to.deep.equal({});
548+
});
549+
});
529550
});

src/util/utility-functions.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,10 @@
77

88
import Logger, { ILogger } from './logger';
99

10+
11+
export interface AnyObject {
12+
[key: string]: any;
13+
}
1014
export interface NestedObject {
1115
[key: string]: any;
1216
}
@@ -396,3 +400,16 @@ export function arrayOf(array: any[], ...types: string[]): boolean {
396400
return types.includes(typeof item);
397401
});
398402
}
403+
404+
405+
/**
406+
* Alphabetically sort object keys
407+
* @param object Object to be sorted
408+
*/
409+
export function sortObjectKeys(object: AnyObject): AnyObject {
410+
return Object.keys(object).sort()
411+
.reduce((sortedObject, key) => ({
412+
...sortedObject,
413+
[key]: object[key],
414+
}), {});
415+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy