I am trying to learn a few new ways to handle lists in javascript. Basicly what this function does is it takes in an array of integers, it tries to find two matches that results in TargetSum, if it does it should return an array of those two sorted.
The issue I am having is that while this returns correct, it can be optimized due to forEach always running the full iteration.
How should I change this into returning as soon as I have a match?
function twoNumberSum(array, targetSum) {
array = array.reduce((acc, curr) => {
acc.set(curr, curr);
return acc;
}, new Map());
let res = [];
array.forEach(item => {
const missingInc = targetSum - item;
if (array.has(missingInc)) {
res = [item, array.get(missingInc)].sort((a, b) => a > b)
}
})
return res;
}
console.log(twoNumberSum([3, 5, -4, 8, 11, 1, -1, 6], 10))