-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy patharray.ts
46 lines (39 loc) · 1.47 KB
/
array.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
export const isFirstOrLastElement = <T>(array: T[], element: T) =>
array[0] === element || array[array.length - 1] === element;
export const isEmptyArray = <T>(array: T[]) => array.length === 0;
/**
* Take an array of strings, sort it and split it in two : one array of letter starting strings and one with digit or special characters starting strings.
*/
export const splitArrayByFirstLetter = (array: string[]): [string[], string[]] => {
if (array.length === 0) return [[], []];
const sortedArray = [...array].sort();
const splittingIndex = sortedArray.findIndex((item) => /^[A-Za-z]/.test(item));
let digitalArray: string[] = [];
let letterArray: string[] = [];
if (splittingIndex === -1) {
// There is no letter starting string in the array
digitalArray = sortedArray;
} else {
digitalArray = sortedArray.slice(0, splittingIndex);
letterArray = sortedArray.slice(splittingIndex);
}
return [digitalArray, letterArray];
};
export const removeElementAtIndex = <T>(array: T[], indexToRemove: number) => {
const result = [...array];
result.splice(indexToRemove, 1);
return result;
};
/**
* returns a copy of the array with an element replaced
*/
export function replaceElementAtIndex<T, K extends Readonly<T[]>>(
array: T[] | K,
indexToReplace: number,
newElement: T
): T[] | K {
const result = [...array];
result.splice(indexToReplace, 1, newElement);
return result;
}
export const removeDuplicates = <T>(array: T[]) => [...new Set(array)];