Created
August 7, 2017 22:30
-
-
Save IronSavior/a7a9fd492188ac97d8dc9c7141e5a956 to your computer and use it in GitHub Desktop.
JavaScript named predicate helper (Symbol#to_proc from Ruby)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"use strict"; | |
// Make predicate funtions more convenient. | |
// Works like Ruby's Symbol#to_proc, which is usually called with the unary & operator and a Symbol literal: | |
// (ruby) %w[one two three].map(&:upcase) # returns ["ONE", "TWO", "THREE"] | |
// (js) ['one', 'two', 'three'].map(toFn('toUpperCase')); // returns ["ONE", "TWO", "THREE"] | |
// (js) ['one', 'two', 'three'].map(toFn`toUpperCase`); // same as above, but called via tagged string literal | |
// @param name {String} Name of method | |
// @param ...bound_args Arguments to bind NOTE: Args cannot be bound when calling as a tagged-template | |
// @return {Function} Function to call named method with bound args on any object given at time of invocation | |
module.exports = function toFn( name, ...bound_args ){ | |
if( name instanceof Array ){ | |
if( name.length > 1 || bound_args.length > 0 ) throw 'Tagged-template calls must not contain expressions'; | |
name = name[0]; | |
} | |
return (obj, ...args) => obj[name](...bound_args, ...args); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment