Created
August 10, 2011 13:34
-
-
Save JamesKyburz/1136808 to your computer and use it in GitHub Desktop.
string to function
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
String.prototype.to_f = function() { | |
var method = this; | |
var arity = method.match(/arity:(\d+)/); | |
var argument_count = -1; | |
if (arity) { | |
arity = arity[1]; | |
argument_count = 1 + arity; | |
} | |
method = method.replace(/\s*arity:\d+/, ''); | |
var passed_args = Array().slice.call(arguments); | |
return function() { | |
var args = Array().slice.call(arguments, 0, argument_count); | |
var obj = args.shift(); | |
var fn = obj[method]; | |
if (fn) { | |
if (typeof fn == 'function') { | |
return fn.apply(obj, passed_args); | |
} else { | |
return fn; | |
} | |
} else { | |
var operands = [obj]; | |
for (var i=0; i < arity; i++) { | |
operands.push(args[i]); | |
}; | |
operands = operands.concat(passed_args); | |
if (typeof obj == 'string') { | |
var quote = obj.match(/"/) ? "'" : '"'; | |
for (var i=0; i < operands.length; i++) { | |
operands[i] = quote + operands[i] + quote; | |
}; | |
} | |
var expression = operands.join(' ' + method + ' '); | |
return eval(expression); | |
} | |
}; | |
}; | |
var u = require('underscore'); | |
> | |
> u([4, 5, 6]).map("+ arity:0".to_f(2)); | |
[ 6, 7, 8 ] | |
> u(['4-4', '5-5', '6-6']).reduce("+ arity:1".to_f('')); | |
'4-45-56-6' | |
> u([4, 5, 6]).reduce("+ arity:1".to_f(0)); | |
15 | |
> u([4, 5, 6]).map(">> arity:0".to_f(1)); | |
[ 2, 2, 3 ] | |
> u([4, 5, 6]).map("<< arity:0".to_f(1)); | |
[ 8, 10, 12 ] | |
> u([4, 5, 6]).reduce("* arity:1".to_f(1)); | |
120 | |
> u([1, 2, 3]).map("+ arity:0".to_f(2)); | |
[ 3, 4, 5 ] | |
> u(['abc', 'defg', 'hijkl']).map('toUpperCase'.to_f()); | |
[ 'ABC', 'DEFG', 'HIJKL' ] | |
> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment