The first is that I don't think you want to do k-=n, rather just k-n. As written, this will only work with pairs with the first number in the array.
Second, you need to limit the includes check to the remainder of the array, or you will fail in cases such as doTheyAddTo([5], 10), because 5 will be considered as a valid addend of itself.
To fix the latter, refactor into a for (let i = 0, n; i < a.length; n = a[i++]) loop to get access to the index, or the much much more readable find, e.g...
functiondoTheAddTo(a,k){a.find((n,i)=>{// because we're in a closure instead of a loop iteration,// we also don't have to worry about prematurely returning false// and can instead just return the value of our checkreturna.includes(k-n,i+1)})}
Note, using find instead of reduce or filter will maintain the short circuit you had.
In JavaScript you could do
looks good, but when you use
includes
is it O(log n) ?jsperf.com/hashtable-vs-includes
Two problems I can find.
The first is that I don't think you want to do
k-=n
, rather justk-n
. As written, this will only work with pairs with the first number in the array.Second, you need to limit the
includes
check to the remainder of the array, or you will fail in cases such asdoTheyAddTo([5], 10)
, because 5 will be considered as a valid addend of itself.To fix the latter, refactor into a
for (let i = 0, n; i < a.length; n = a[i++])
loop to get access to the index, or the much much more readablefind
, e.g...Note, using
find
instead ofreduce
orfilter
will maintain the short circuit you had.Your function does not return anything though. Even if you do return the value of the initial find it won't be a Boolean.
whoops. too much REPL, not enough real code. Should be
return typeof a.find(...) !== 'undefined'
.