Skip to content

Instantly share code, notes, and snippets.

@Slackwise
Created February 10, 2020 14:34
Show Gist options
  • Save Slackwise/10a52386b8c1f5e8bf580ab55a857297 to your computer and use it in GitHub Desktop.
Save Slackwise/10a52386b8c1f5e8bf580ab55a857297 to your computer and use it in GitHub Desktop.
Arity matching functions in JavaScript
// Example 1 or 2-arity function f
const f = (...args) =>
[
(x) => console.log("One param"),
(x, y) => console.log("Two params")
][args.length-1](...args);
f(1) // "One param"
f(1, 2) // "Two param"
// Abstracted into a higher order function
const arityMatch = (...fns) =>
(...args) =>
[...fns][args.length-1](...args);
const f2 = arityMatch(
(x) => console.log("One param"),
(x, y) => console.log("Two param")
);
f2(1) // "One param"
f2(1, 2) // "Two param"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment