Skip to content

Instantly share code, notes, and snippets.

@FireyFly
Created June 15, 2012 15:34
Show Gist options
  • Save FireyFly/2937067 to your computer and use it in GitHub Desktop.
Save FireyFly/2937067 to your computer and use it in GitHub Desktop.
var f = wrapFunc(function() {
function Fraction(nom, denom) {
this.nominator = nom
this.denominator = denom
}
Fraction.prototype['*'] = function(other) {
return new Fraction(this.nominator * other.nominator,
this.denominator * other.denominator)
}
Fraction.prototype.toString = function() {
return this.nominator + "/" + this.denominator
}
var one_half = new Fraction(1, 2)
, one_third = new Fraction(1, 3)
return one_half * one_third
})
console.log(String(f())) // 1/6
var falafel = require('falafel')
, assert = require('assert')
// Preparations
Number.prototype['+'] = function(other) { return this + other }
Number.prototype['-'] = function(other) { return this - other }
Number.prototype['*'] = function(other) { return this * other }
Number.prototype['/'] = function(other) { return this / other }
String.prototype['+'] = function(other) { return this + other }
function wrapFunc(fn) {
assert.equal(typeof fn, 'function', "Passed non-function to wrapFunc!")
var processed = process("(" + fn + ")")
, newParts = explodeFunction(processed.toString())
return Function(newParts.args, newParts.body)
function process(body) {
return falafel(body, function(node) {
if (node.type == 'BinaryExpression') {
node.update( wrap("%s", node.left.source())
+ wrap("['%s']", node.operator)
+ wrap("(%s)", node.right.source()))
}
})
function wrap(format, other) {
return format.replace(/%s/g, other)
}
}
function explodeFunction(str) {
if (str[0] == '(' && str.slice(-1) == ')') {
// Unwrap parenthesized function: ((((x)))) --> x
return explodeFunction(str.slice(1, -1))
}
var match = str.match(/^function\s*(\w*)\s*\(([^)]*)\)\s*{([\s\S]*)}$/)
assert.ok(match, "Couldn't explode function!")
var name = match[1]
, args = match[2]
, body = match[3]
return { name:name, args:args, body:body }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment