I want to solve the given problem to make reasoning about higher order functions easier for me in the future. Given an array of ones and zeroes, we need to find the elements that are surrounded by ones.
// 0 1 2 3 4 5 6 7 8 9101112
const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
//The above array has 3 bombs, being 0 1 and 0 at positions 7, 9, and 11.
//What I want to do is filter the array for the bombs, using a function such as this:
const bombs = bombfield.filter((x) => (y) => (z) => (x == 1 && z == 1));
// What I expect this to return through currying is those elements that have 1 as each of their neighbors.
CodePudding user response:
There's no currying going on here. bombfield.filter()
just checks whether the return value of the callback function is truthy or not. If the returned value is a function, it won't call it again. Since all functions are truthy, this filter succeeds for every element, and just returns a copy of the array.
And even if it did, it wouldn't call it with surrounding elements.
The second argument to the callback function is the array index, and the third argument is the array being filtered. You can use that to access other elements of the same array.
const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
const bombs = bombfield.filter((x, i, arr) => arr[i-1] === 1 && arr[i 1] === 1);
console.log(bombs);
CodePudding user response:
As Barmer said, you don't have to curry anything here, There is a way to get the indexes which you may need as well.
const bombfield = [0,0,1,1,0,0,1,0,1,1,1,0,1];
const bombIndexes = [];
bombfield.forEach((element, index, array) => {
if (array[index-1] === 1 && array[index 1] === 1) bombIndexes.push(index);
});
const bombs = bombfield.filter((element, index, array) => array[index-1] === 1 && array[index 1] === 1);
console.log("Bomb Indexes: ", bombIndexes);
console.log("Bomb Values: ", bombs);