Skip to content

Instantly share code, notes, and snippets.

@dereknahman
Created October 5, 2020 10:27
Show Gist options
  • Save dereknahman/a74f9376bcb6bd6650578fb11ff8fcbd to your computer and use it in GitHub Desktop.
Save dereknahman/a74f9376bcb6bd6650578fb11ff8fcbd to your computer and use it in GitHub Desktop.
The problem: Use forEach to write a function that behaves like filter.
The correct answer:
function filter(arr, callback) {
const newArr = [];
arr.forEach((el) => {
if (callback([el])) {
newArr.push(el)
}
})
return newArr;
}
The tests that had to pass:
>
filter([1, 2, 3], num => num >= 0)
Expected: [1, 2, 3] OK!
>
filter([1, 2, 3], num => num > 1)
Expected: [2, 3] OK!
>
filter([1, 2, 3], num => num > 5)
Expected: [] OK!
>
filter([null, undefined], num => true)
Expected: [null, undefined] OK!
>
filter([], num => true)
Expected: [] OK!
>
// You must use `forEach`.
filter.toString().includes('forEach')
Expected: true OK!
>
// You must use a stack function.
const code = filter.toString()
code.includes('pop') || code.includes('push')
Expected: true OK!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment