Skip to content

Instantly share code, notes, and snippets.

@gunar
Last active November 11, 2019 22:20
Show Gist options
  • Save gunar/1268c997ca66343f060dbca07aee67bd to your computer and use it in GitHub Desktop.
Save gunar/1268c997ca66343f060dbca07aee67bd to your computer and use it in GitHub Desktop.
Currying Functions with Named Parameters in JavaScript
/**
* Currying Functions with Named Parameters.
* @gunar, @drboolean, @dtipson 2016
*
* Why does it return a thunk, though?
* Because in JS named arguments are opaque. There is no way of getting a function's named arguments list.
* e.g.
* const foo = function ({ a, b }) { }
* console.log(foo.arguments) // Throws. Ideally would return ['a', 'b'].
*
* What would be an alternative?
* Providing a "spec". curryNamed would have to be told what the named arguments were upfront
* (as curryN does with numbered arguments). I personally think that's less useful.
*/
'use strict'
function curryNamed(fn, acc = {}) {
return args => {
if (!args) return fn(acc)
return curryNamed(fn, Object.assign({}, acc, args))
}
}
const foo = ({ a, b, c } = {}) => console.log({ a, b, c })
const bar = curryNamed(foo)
bar() // { a: undefined, b: undefined, c: undefined }
const a = bar({ a: 1 })
a() // { a: 1, b: undefined, c: undefined }
const ab = a({ b: 2 })
ab() // { a: 1, b: 2, c: undefined }
bar({ a: 1, b: 2, c: 3 })() // { a: 1, b: 2, c: 3 }
@gunar
Copy link
Author

gunar commented Jul 13, 2017

There y'all go

https://github.com/gunar/ncurry

It accepts partial application and stuff.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment