Skip to content

Commit 3abe543

Browse files
Added missing general functions for enum to array
1 parent 30cbee4 commit 3abe543

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

case-types-parser.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,4 +31,11 @@ export function snakeCaseToCamelCase(str: string) {
3131
.toUpperCase()
3232
.replace('_', '')
3333
);
34+
}
35+
36+
export enum caseType {
37+
LOWER,
38+
UPPER,
39+
CAPITALIZE_FIRST,
40+
CAPITALIZE_FIRST_PER_WORD
3441
}

general.ts

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
import { capitalizeFirst, capitalizeFirstPerWord, caseType } from "./case-types-parser";
2+
13
export function jsonCopy(src: any): any {
24
return JSON.parse(JSON.stringify(src));
35
}
@@ -107,4 +109,37 @@ export function formatBytes(bytes, decimals = 2) {
107109
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
108110
const i = Math.floor(Math.log(bytes) / Math.log(1024));
109111
return parseFloat((bytes / Math.pow(1024, i)).toFixed(dm)) + ' ' + sizes[i];
110-
}
112+
}
113+
114+
115+
export type enumToArrayOptions = {
116+
caseType?: caseType;
117+
prefix?: string;
118+
nameFunction?: (name: string) => string;
119+
}
120+
121+
export function enumToArray(e: Object, options: enumToArrayOptions = null): any[] {
122+
const arr = Object.values(e);
123+
if (!options) return sortByEnumPos(e, arr);
124+
let func;
125+
if (options.caseType == caseType.LOWER) func = (x) => x.toLowerCase();
126+
else if (options.caseType == caseType.UPPER) func = (x) => x.toUpperCase();
127+
else if (options.caseType == caseType.CAPITALIZE_FIRST) func = capitalizeFirst;
128+
else if (options.caseType == caseType.CAPITALIZE_FIRST_PER_WORD) func = capitalizeFirstPerWord;
129+
130+
if (func) return enumToArray(e, { prefix: options.prefix, nameFunction: func });
131+
if (!options.nameFunction) return sortByEnumPos(e, arr.map(x => ({ name: options.prefix + x, value: x })));
132+
return sortByEnumPos(e, arr.map(x => ({ name: (options.prefix ? options.prefix : "") + options.nameFunction(x), value: x })));
133+
}
134+
135+
function sortByEnumPos(e: Object, arr: any[]) {
136+
const order = [];
137+
for (let key in e) {
138+
order.push(key);
139+
}
140+
return arr.sort((a, b) => {
141+
const index1 = order.findIndex(key => e[key] === a.code);
142+
const index2 = order.findIndex(key => e[key] === b.code);
143+
return index1 - index2;
144+
});
145+
}

0 commit comments

Comments
 (0)