Skip to content

Instantly share code, notes, and snippets.

@vuldin
Created March 28, 2018 08:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vuldin/e1f5c9eeb3e1b069e542f73e86888917 to your computer and use it in GitHub Desktop.
Save vuldin/e1f5c9eeb3e1b069e542f73e86888917 to your computer and use it in GitHub Desktop.
an add closure that takes any number of arguments and/or parameters

This module exports an add closure that takes any number of arguments and/or parameters

Examples:

add()
add(1)
add(1,2)
add(1)(2)
add(1,2)(3,4)

Each given number is added together and the result is returned. The trick is the use of Symbol.toPrimitive, which allows the returned function to be turned into a number. Wrap the function call in Number() to print the resulting number. Example: Number(add(1)(2,3)(4)(-100)(123))

This stack overflow comment was helpful in showing how to spread arguments inside function and suggesting to bind 0 to the function instead of handling value inside function https://stackoverflow.com/a/34776276/2316606

module.exports = function add() {
// 'use strict' is needed so this in the add function doesn't refer to global environment
'use strict'
// an array of all args plus value of this is reduced to a single value
const sum = [this, ...arguments].reduce((prev, curr) => prev + curr)
// bind this value to the function and save into new result object
const result = add.bind(sum)
// define the toPrimitive symbol function to return the sum
result[Symbol.toPrimitive] = () => sum
return result
}.bind(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment