-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.ts
75 lines (68 loc) · 1.92 KB
/
utils.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
/** Creates an interval of values */
/**
* Creates an interval of values
* @param lbound Lower boundary
* @param ubound Upper boundary
* ```
* createInterval(4, 8); // Returns: [4, 5, 6, 7, 8]
* ```
*/
export function createInterval(lbound: number, ubound: number): number[] {
const res: number[] = [];
for (let i = lbound; i < ubound + 1; i++) {
res.push(i);
}
return res;
}
/**
* Predicate function for Array.prototype.filter() to remove duplicates
* @param value element of the array
* @param index index of the element
* @param self array that contains the element
* ```
* findKey({a: "A", b: "B"}, "B"); // Returns: "b"
* findKey({a: "A", b: "B"}, "C"); // Returns: undefined
* ```
*/
export function findKey<T extends Record<string, unknown>>(
obj: T,
search: unknown,
): string | undefined {
const keys = Object.keys(obj) as (string)[];
return keys.find((key) => {
return obj[key] === search;
});
}
/**
* Predicate function for Array.prototype.filter() to remove undefined values
* @param value element of the array
* ```
* [0, false, null, "a", void 0].filter(removeUndefined); // Returns: [0, false, null, "a"]
* ```
*/
export function removeUndefined<T>(value?: T): value is T {
return value !== void 0;
}
/**
* Allows Array.prototype.sort() to sort a numeric array in ascending order
* @param a number
* @param b number
* ```
* [2,3,1].sort(sortNumericArrayASC) // Returns: [1,2,3]
* ```
*/
export function sortNumericArrayASC(a: number, b: number): number {
return a - b;
}
/**
* Predicate function for Array.prototype.filter() to remove duplicates
* @param value element of the array
* @param index index of the element
* @param self array that contains the element
* ```
* [1,2,3,2,1].filter(unique); // Returns: [1,2,3]
* ```
*/
export function unique<T>(value: T, index: number, self: T[]): boolean {
return self.indexOf(value) === index;
}