How do I do X using Y ?
Generally I approach all of these questions the same way: programming languages aren't meant to be magic wands. If your language doesn't come with a built-in feature or behaviour, you should be able to write it on your own. From there, if you later learn that your language does offer a built-in for such a behaviour (or it is added), then you can refactor your code if you wish. But by all means, do not sit around waiting for the magic wand to be waved and for your code to magically work.
You can use Array.prototype.reduce
if you want, but given the way it works, it will always iterate through the entire contents of the array — even if a match is found in the first element. So this means you shouldn't use Array.prototype.reduce
for your function.
However, you can use a reduce solution if you write a reduce
which supports an early exit. Below is reducek
which passes a continuation to the callback. Applying the continuation will continuing reducing, but returning a value will perform an early exit. Sounds like exactly what the doctor ordered...
This answer is meant to accompany LUH3417's answer to show you that before you might be aware of Array.prototype.some
, you shouldn't sit around waiting for ECMAScript to implement behaviour that you need. This answer demonstrates you can use a reducing procedure and still have early exit behaviour.
const reducek = f=> y=> ([x,...xs])=>
x === undefined ? y : f (y) (x) (y=> reducek (f) (y) (xs))
const contains = x=>
reducek (b=> y=> k=> y === x ? true : k(b)) (false)
console.log(contains (4) ([1,2,3,4,5])) // true
console.log(contains (4) ([1,2,3,5])) // false
console.log(contains (4) ([])) // false
Seeing reducek
here and the example contains
function, it should be somewhat obvious that contains
could be generalized, which is exactly what Array.prototype.some
is.
Again, programming isn't magic, so I'll show you how you could do this if Array.prototype.some
didn't already exist.
const reducek = f=> y=> ([x,...xs])=>
x === undefined ? y : f (y) (x) (y=> reducek (f) (y) (xs))
const some = f=>
reducek (b=> x=> k=> f(x) ? true : k(b)) (false)
const contains = x=> some (y=> y === x)
console.log(contains (4) ([1,2,3,4,5])) // true
console.log(contains (4) ([1,2,3,5])) // false
console.log(contains (4) ([])) // false