Accepting functions as arguments
suggest changefunction transform(fn, arr) {
const result = [];
for (const el of arr) {
result.push(fn(el)); // We push the result of the transformed item to result
}
return result;
}
console.log(transform(x => x * 2, [1,2,3,4])); // [2, 4, 6, 8]
As you can see, transform accepts two parameters, a function and a collection. It iterates the collection and pushes the value returned by fn for each element.
Looks familiar? This is very similar to how Array.prototype.map() works!
console.log([1, 2, 3, 4].map(x => x * 2)); // [2, 4, 6, 8]
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents