The task
...is taken from leetcode
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums1 = 2 + 7 = 9, return [0, 1].
const lst = [11, 7, 15, 2]
const target = 9;
My imperative solution
function findIndexOfSumPair(lst, trgt) {
const len = lst.length;
for (let i = 0; i < len; i++) {
const found = lst.findIndex(x => trgt - lst[i] === x);
if (found !== i && found !== -1) {
return [found, i];
}
}
}
console.log(findIndexOfSumPair(lst, target));
My functional solution
const findIndexOfSumPair2 = (lst, trgt) => {
return lst.reduce((res, x, i) => {
const j = lst.findIndex(y => target - x === y);
return j !== -1 ? [i, j] : res;
});
};
console.log(findIndexOfSumPair2(lst, target));
The disadvantage with my functional solution is that reduce iterates till the end of the array - even though it may have found a solution already. I tried to come up with a functional that stops iterating once it found a solution. I could come up with this. However it is too verbose and relies on side-effects (which doesn't make it functional anymore):
const findIndexOfSumPair3 = (lst, trgt) => {
let res;
lst.some((x, i) => -1 !== lst.findIndex((y, j) => {
if (i !== j && trgt - y === x) {
res = [j, i];
return true;
}
}));
return res;
};
console.log(findIndexOfSumPair3(lst, target));
Do you know an elegant and efficient functional solution?