Problem statement
Write a function that takes in a non-empty array of distinct integers and an integer representing a target sum.
If any two numbers in the input array sum up to the target sum, the function should return them in an array, in any order. If no two numbers sum up to the target sum, the function should return an empty array.
Solution
Since we want to deduce a value from list, reduce function will be appropriate to solve the problem. Set up an object that keeps a track of items from the list and if the difference between the current item and targeted number is present in the object, update the list with current item
typescript
export function twoNumberSum(array: number[], targetSum: number) {
const initialValue: Array<number> = [];
const isTraversed: {[key: number]: boolean} = {};
return array.reduce((acc: Array<number>, curr: number) => {
const expectedValue = targetSum - curr;
if(expectedValue in isTraversed) {
return [...acc, curr, expectedValue,];
}else {
isTraversed[curr] = true;
}
return acc;
}, initialValue);
}