-
Notifications
You must be signed in to change notification settings - Fork 10
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Sort Questionnaire keys for readability. Closes #96
- Loading branch information
Showing
2 changed files
with
48 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
type JSONObject = { [key: string]: any }; | ||
type JSONArray = Array<any>; | ||
|
||
export function sortKeys<T extends JSONArray | JSONObject>(obj: T, order: string[]): T { | ||
order = order.includes('*') ? order : [...order, '*']; | ||
|
||
if (Array.isArray(obj)) { | ||
return obj.map((element) => sortKeys(element, order)) as T; | ||
} | ||
|
||
if (typeof obj !== 'object' || obj === null) { | ||
return obj; | ||
} | ||
|
||
const keys = Object.keys(obj); | ||
|
||
const sortedKeys = order.flatMap((key) => { | ||
if (key === '*') { | ||
return keys.filter((k) => !order.includes(k)); | ||
} | ||
return keys.includes(key) ? key : []; | ||
}); | ||
|
||
const unmatchedKeys = keys.filter((k) => !sortedKeys.includes(k)); | ||
const finalKeys = [...sortedKeys, ...unmatchedKeys]; | ||
|
||
const sortedObj: JSONObject = {}; | ||
for (const key of finalKeys) { | ||
sortedObj[key] = sortKeys(obj[key], order); | ||
} | ||
|
||
return sortedObj as T; | ||
} |