-
Notifications
You must be signed in to change notification settings - Fork 0
/
toggle-item-in-array.js
37 lines (26 loc) · 1.01 KB
/
toggle-item-in-array.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
/*
toggle function adds or removes a value from an array
it accepts three parameters:
1) an array
2) a value
3) a funcion to validate the value (optional parameter)
if the array actually includes the value then it removes the value from the array
if not then it adds the value to the array
** example:
let arr = [12]
toggle(arr,'bad',(v)=>v!=='bad') // will not add because the value is not valid
*/
const toggle = (array, value, validationFunction = (v) => v || true) => {
let index = array.indexOf(value); // to get the index of the value if it's in array
if(!validationFunction(value)){
return;
}
if(array.includes(value)){ // if array includes the value
array.splice(index,1); // remove value from array
return;
}
array.push(value); // else, add value to array
}
if(typeof exports != 'undefined'){
exports.toggle = toggle
}