-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparseStringToIntegerArray.ts
More file actions
36 lines (27 loc) · 994 Bytes
/
parseStringToIntegerArray.ts
File metadata and controls
36 lines (27 loc) · 994 Bytes
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
/**
* Converts a string to an array of numbers
* @param integerArrayString - A string representing a array of integers (i.e. [16, 87, 27])
* @return An array of integers represented by the string
*/
export function parseStringToIntegerArray(integerArrayString: string) {
if (integerArrayString === "[]") {
return [];
}
if (
integerArrayString.substr(0, 1) !== "[" ||
integerArrayString.substr(integerArrayString.length - 1, 1) !== "]"
) {
throw new Error("The given string is not contained in brackets '[]'");
}
console.log("HI");
// Removing the outter brackets
integerArrayString = integerArrayString.substr(1, integerArrayString.length - 2);
console.log(integerArrayString);
const arrayOfStrings: string[] = integerArrayString.split(",");
const arrayOfInteger: number[] = [];
arrayOfStrings.forEach((numberString: string) => {
arrayOfInteger.push(Number.parseInt(numberString, 10));
});
return arrayOfInteger;
}
export default parseStringToIntegerArray;