-
Notifications
You must be signed in to change notification settings - Fork 770
/
helpers.ts
88 lines (73 loc) · 2.5 KB
/
helpers.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import * as d from '../declarations';
import { normalizePath } from './normalize-path';
export const isDef = (v: any) => v != null;
export const toLowerCase = (str: string) => str.toLowerCase();
export const toDashCase = (str: string) => toLowerCase(str.replace(/([A-Z0-9])/g, g => ' ' + g[0]).trim().replace(/ /g, '-'));
export const dashToPascalCase = (str: string) => toLowerCase(str).split('-').map(segment => segment.charAt(0).toUpperCase() + segment.slice(1)).join('');
export const toTitleCase = (str: string) => str.charAt(0).toUpperCase() + str.slice(1);
export const noop = (): any => { /* noop*/ };
export const isComplexType = (o: any) => {
o = (typeof o)[0];
return o === 'o' || o === 'f';
};
export const sortBy = <T>(array: T[], prop: ((item: T) => string | number)) => {
return array.slice().sort((a, b) => {
const nameA = prop(a);
const nameB = prop(b);
if (nameA < nameB) return -1;
if (nameA > nameB) return 1;
return 0;
});
};
export const flatOne = <T>(array: T[][]): T[] => {
if (array.flat) {
return array.flat(1);
}
return array.reduce((result, item) => {
result.push(...item);
return result;
}, [] as T[]);
};
export const unique = <T>(array: T[], predicate: (item: T) => any = (i) => i): T[] => {
const set = new Set();
return array.filter(item => {
const key = predicate(item);
if (key == null) {
return true;
}
if (set.has(key)) {
return false;
}
set.add(key);
return true;
});
};
export const fromEntries = <V>(entries: IterableIterator<[string, V]>) => {
const object: { [key: string]: V} = {};
for (const [key, value] of entries) {
object[key] = value;
}
return object;
};
export const relativeImport = (config: d.Config, pathFrom: string, pathTo: string, ext?: string, addPrefix = true) => {
let relativePath = config.sys.path.relative(config.sys.path.dirname(pathFrom), config.sys.path.dirname(pathTo));
if (addPrefix) {
if (relativePath === '') {
relativePath = '.';
} else if (relativePath[0] !== '.') {
relativePath = './' + relativePath;
}
}
return normalizePath(`${relativePath}/${config.sys.path.basename(pathTo, ext)}`);
};
export const pluck = (obj: {[key: string]: any }, keys: string[]) => {
return keys.reduce((final, key) => {
if (obj[key]) {
final[key] = obj[key];
}
return final;
}, {} as {[key: string]: any});
};
export const isObject = (val: Object) => {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
};