Nice Agency Interview Question: Write a function that satisfi... | Glassdoor.co.uk

Interview Question

Front End Developer Interview London, England

Write a function that satisfies the following

 : add(1)(2).value() = 3; add(1, 2)(3).value() = 6; add(1)(2)(3).value() = 6; add(1)(2) + 3 = 6;
Answer

Interview Answer

1 Answer

0

const add = (...args) => {
  let total = 0

  const wrapper = (...args) => {
    const addToTotal = (...args) => {
      total += args.reduce((a, b) => a + b, 0)
    }

    addToTotal(...args)

    return wrapper
  }

  wrapper.value = () => total
  wrapper.valueOf = () => total

  return wrapper(...args)
}

module.exports = add

Interview Candidate on 28 Mar 2017

Add Answers or Comments

To comment on this, Sign In or Sign Up.