Skip to content

Instantly share code, notes, and snippets.

@tvardy
Last active July 1, 2017 20:10
Show Gist options
  • Select an option

  • Save tvardy/ec9dd74818606bf053d4457f67a7910c to your computer and use it in GitHub Desktop.

Select an option

Save tvardy/ec9dd74818606bf053d4457f67a7910c to your computer and use it in GitHub Desktop.

Revisions

  1. tvardy renamed this gist Jul 1, 2017. 1 changed file with 0 additions and 0 deletions.
    File renamed without changes.
  2. tvardy created this gist Jul 1, 2017.
    18 changes: 18 additions & 0 deletions console output
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,18 @@
    2.25
    4
    6
    6.99
    9
    12
    16
    20
    24
    27
    60
    6000
    Hello, world!
    Hello, cousin!
    Hello, babe!
    Good bye, cruel world!
    Very good bye, for ever!!!
    -= END =-
    62 changes: 62 additions & 0 deletions curry.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,62 @@
    // the prime hero here
    function curry(func, expectedCount, ...args) {
    function _check(arr) {
    return arr.length >= expectedCount ? _result(arr) : _curry.bind(null, arr)
    }

    function _curry(prev, ...rest) {
    return _check(prev.concat(rest))
    }

    function _result(arr) {
    return func.apply(this, arr)
    }

    return _check(args)
    }

    // 2 simple "workers" to apply currying on
    function multiplyAll(...arr) {
    return arr.reduce((p, c) => p * c, 1)
    }

    function sayTo(type, target, end = '!') {
    return `${type}, ${target}${end}`
    }

    // helper logger
    function log(...args) {
    console.log(args.join('\n'))
    }

    // definitions
    const multiply = curry(multiplyAll, 2) // uses `multiplyAll` worker, expects at least 2 arguments
    const double = multiply(2) // multiples by 2
    const triple = multiply(3) // multiples by 3
    const say = curry(sayTo, 2) // uses `sayTo` worker, expects at least 2 arguments
    const sayHello = say('Hello') // says "Hello, [argument]!"
    const sayHelloBabe = () => sayHello('babe') // says "Hello, babe!"
    const sayGoodBye = say('Good bye') // says "Good bye, [argument]"
    const sayVeryGoodBye = curry(sayTo, 2)('Very good bye') // says "Very good bye, [argument]"

    // running test
    log(
    multiply(1.5)(1.5),
    double(2),
    multiply(2, 3),
    triple(2.33),
    multiply(3)()(3),
    curry(multiplyAll, 3, 2, 3, 2),
    double(2, 4),
    multiply()(4)()(5),
    double(triple(4)),
    triple(3, 3),
    multiply()(3)(4, 5),
    curry(multiplyAll, 3)(10)(20)(30),
    sayHello('world'),
    sayHello()('cousin'),
    sayHelloBabe(),
    sayGoodBye('cruel world'),
    sayVeryGoodBye('for ever', '!!!'),
    '-= END =-'
    )