-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtakeUntil.js
43 lines (37 loc) · 1.14 KB
/
takeUntil.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
const eqArrays = function(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
};
const assertArraysEqual = function(arr1, arr2) {
if (eqArrays(arr1, arr2)) {
console.log(`✅✅✅ Assertion Passed: ${arr1} === ${arr2}`);
} else {
console.log(`🛑🛑🛑 Assertion Failed: ${arr1} !== ${arr2}`);
}
};
const takeUntil = function(array, callback) {
let results = [];
for (let element of array) {
if (!callback(element)) {
results.push(element);
} else {
return results;
}
}
return results;
};
//will return a slice of the array with elemetns taken from the beginning; keeps going until callback returns a truthy value
const data1 = [1, 2, 5, 7, 2, -1, 2, 4, 5];
const results1 = takeUntil(data1, x => x < 0);
assertArraysEqual(results1, [1, 2, 5, 7, 2]);
console.log('---');
const data2 = ["I've", "been", "to", "Hollywood", ",", "I've", "been", "to", "Redwood"];
const results2 = takeUntil(data2, x => x === ',');
assertArraysEqual(results2, ["I've", "been", "to", "Hollywood"]);