Quick actions

cmd+k|ctrl+k

Navigation

Languages

Carrying

Snippet info

Language

JavaScript

Visibility

public

Author

paulkotov

Created

2018-12-08T10:55:25Z

Updated

2021-06-10T06:15:30.891662Z

// Given an array of numbers, if the index is even, add.
//   If the index is odd, subtract.
const addSubtractReducer = (total, current, index) =>
  (index % 2) === 0 ?
    total + current :
    total - current;
    
const addSubtract = (x) => {
  const nums = [];
  // Recursive function that accumulates numbers for the operation.
  const f = (y) => {
    nums.push(y);
    return f;
  };
  // When the recursive function is type cast to a number,
  //   reduce the accumulated numbers.
  f.valueOf = () => nums.reduce(addSubtractReducer, x);
  // Return the recursive function, having added the first digit.
  return f;
};

const addTo1 = addSubtract(1);
let x = addTo1(2);
console.log(x.valueOf());
INFO