How to refactor this function to a higher order function?
It is meant to return a new array containing the sub-arrays of characters that contain the value 'Rambo'.
function isRamboCharacter(characters) {
const x = [];
for (let i = 0; i < characters.length; i ) {
if (characters[i].movie.includes('Rambo')) {
x.push(characters[i]);
}
}
return x;
}
I tried:
return characters.movie.includes('Rambo');
CodePudding user response:
Solution
const characters = [
{ movie: ["Rambo", "Rockey", "Avengers"] },
{ movie: ["Fatherhood", "Rockey", "Avengers"] }
]
const isRamboCharacter = (characters) => characters.filter((char) => char.movie.includes("Rambo"))
console.log(isRamboCharacter(characters));
Or you could directly call Array's filter method
console.log(characters.filter((char) => char.movie.includes("Rambo")));
//output - [ { movie: [ 'Rambo', 'Rockey', 'Avengers' ] } ]
CodePudding user response:
You can curry it (Return a function in a function)
function isCharacterInMovie(movie) {
return function filterFunction(characters) {
const x = [];
for (let i = 0; i < characters.length; i ) {
if (characters[i].movie.includes(movie)) {
x.push(characters[i]);
}
}
return x;
}
}
const isRamboInMovie = isCharacterInMovie('rambo') // returns the inner function which holds on to the value from when you called it
isRamboInMovie(charactersInTheMatrix); // []
isRamboInMovie(charactersInRambo); // ['rambo']
The 'You don't know JS' book series has a great (short AND free) book on this, and it explains it incredibly well You Don't Know JS Yet: Scope & Closures - 2nd Edition