-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
52 lines (37 loc) · 1.34 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//// util
type OrderableValue = string | number | boolean | null | undefined | OrderableObject | OrderableValue[];
interface OrderableObject {
[key: string]: OrderableValue;
}
//// export
/**
* Recursively orders an object's keys and its nested objects alphabetically
* ```ts
* import { orderObject } from "jsr:@netopwibby/order-object";
*
* console.log(orderObject({ zebra: "yay", 1: "neo", horse: "neigh" }));
* // returns { "1": "neo", horse: "neigh", zebra: "yay" }
*
* @param value - The value to order (object, array, or primitive)
* @returns The ordered value, or the original value if not orderable
*/
export function orderObject<T extends OrderableValue>(value?: T): T | null {
if (value === null || value === undefined)
return null;
if (Array.isArray(value)) // recursively order array elements
return value.map(item => orderObject(item)) as T;
if (typeof value !== "object")
return value;
const sortedKeys = Object.keys(value).sort();
// recursively order key values
const orderedObject = sortedKeys.reduce<OrderableObject>((result, key) => {
const currentValue = (value as OrderableObject)[key];
result[key] = orderObject(currentValue);
return result;
}, {});
// preserve original object's prototype
return Object.setPrototypeOf(
orderedObject,
Object.getPrototypeOf(value)
) as T;
}