-
Notifications
You must be signed in to change notification settings - Fork 0
/
_.js
81 lines (68 loc) · 1.99 KB
/
_.js
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
const _ = {
clamp(num, lowerBound, upperBound) {
return Math.min(Math.max(num, lowerBound), upperBound);
},
inRange(num, start, end) {
if (end == undefined) { // check if end is undefined
end = start;
start = 0;
}
if (start > end) { // swap start and end if in wrong order
let temp = start;
start = end;
end = temp;
}
return num >= start && num < end ? true : false;
},
words(string) {
return string.split(' ');
},
pad(string, length) {
if (string.length >= length) return string;
let startPad = Math.floor((length - string.length) / 2);
let endPad = length - string.length - startPad;
const space = ' ';
return space.repeat(startPad) + string + space.repeat(endPad);
},
has(object, property) {
return Object.hasOwn(object, property);
},
invert(object) {
const invObject = {};
for (const key in object) {
invObject[object[key]] = key;
}
return invObject;
},
findKey(object, func) {
for (const key in object) {
if (func(object[key]) == true) return key;
}
return undefined;
},
drop(array, num) {
const newArray = [];
if (num == undefined) num = 1;
for (let i = num; i < array.length; i++) {
newArray.push(array[i]);
}
return newArray;
},
dropWhile(array, func) {
for (let i = 0; i < array.length; i++) {
if (func(array[i], i, array) == false) {
return array.slice(i);
}
}
},
chunk(array, size) {
const chunkArray = [];
if (size == undefined) size = 1;
for (let i = 0; i < array.length; i = i + size) {
chunkArray.push(array.slice(i, i + size));
}
return chunkArray;
}
};
// Do not write or modify code below this line.
module.exports = _;