-
Notifications
You must be signed in to change notification settings - Fork 0
/
_.js
106 lines (89 loc) · 2.55 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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
const _ = {
clamp(number,lowerBound,upperBound) {
return number < lowerBound ? lowerBound : number > upperBound ? upperBound : number
},
inRange (number, start, end){
if(!end){
end = start;
start = 0;
}
if(start > end) {
let val = end;
end = start;
start = val;
}
return (number >= start && number < end);
},
words(sentence){
let chars = '';
let words = [];
for(let i = 0; i < sentence.length; i++){
if(sentence[i] != ' '){chars = chars + sentence[i]; continue;}
if((sentence[i] === ' ' || i === sentence.length - 1) && chars != ''){
words.push(chars);
chars = '';
}
}
if(chars != ''){
words.push(chars);
chars = '';
}
return words;
},
pad(string, length){
if(string.length >= length) return string;
let numPads = length - string.length;
let newString = '';
for(let i = 1; i * 2 <= numPads; i++){
newString = newString + ' ';
}
newString = newString + string;
for(let i = 1; i * 2 <= numPads + 1; i++){
newString = newString + ' ';
}
return newString;
},
has(obj, key){
return obj[key] === undefined ? false : true;
},
invert(obj){
newObj = {};
objKeys = Object.keys(obj);
for(let i = 0; i < objKeys.length; i++){
newObj[obj[objKeys[i]]] = objKeys[i];
}
return newObj;
},
findKey(obj, func){
objKeys = Object.keys(obj);
for(let i = 0; i < objKeys.length; i++){
if(func(obj[objKeys[i]])) return objKeys[i];
}
return undefined;
},
drop(array, elementsToDrop = 1){
return array.slice(elementsToDrop);
},
dropWhile(array, predFunc){
let index = 0;
let element = array[index];
while(predFunc(element, index, array)){
index++;
element = array[index];
}
return this.drop(array, index);
}
};
function measureRuntime(func, iterations = 1, ...rest){
const { performance } = require('perf_hooks');
if(iterations < 1) return NaN;
let start = performance.now();
for(let i = 1; i <= iterations; i++){
func(...rest);
}
return (performance.now()-start)/iterations;
}
let input = undefined
iterations = 100;
// Do not write or modify code below this line.
module.exports = _;