Guest User

Untitled

a guest
Oct 20th, 2018
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.45 KB | None | 0 0
  1. var falafel = require('falafel')
  2. , assert = require('assert')
  3.  
  4.  
  5. // Preparations
  6. Number.prototype['+'] = function(other) { return this + other }
  7. Number.prototype['-'] = function(other) { return this - other }
  8. Number.prototype['*'] = function(other) { return this * other }
  9. Number.prototype['/'] = function(other) { return this / other }
  10.  
  11. String.prototype['+'] = function(other) { return this + other }
  12.  
  13.  
  14. function wrapFunc(fn) {
  15. assert.equal(typeof fn, 'function', "Passed non-function to wrapFunc!")
  16.  
  17. var processed = process("(" + fn + ")")
  18. , newParts = explodeFunction(processed.toString())
  19.  
  20. return Function(newParts.args, newParts.body)
  21.  
  22. function process(body) {
  23. return falafel(body, function(node) {
  24. if (node.type == 'BinaryExpression') {
  25. node.update( wrap("%s", node.left.source())
  26. + wrap("['%s']", node.operator)
  27. + wrap("(%s)", node.right.source()))
  28. }
  29. })
  30.  
  31. function wrap(format, other) {
  32. return format.replace(/%s/g, other)
  33. }
  34. }
  35.  
  36. function explodeFunction(str) {
  37. if (str[0] == '(' && str.slice(-1) == ')') {
  38. // Unwrap parenthesized function: ((((x)))) --> x
  39. return explodeFunction(str.slice(1, -1))
  40. }
  41.  
  42. var match = str.match(/^function\s*(\w*)\s*\(([^)]*)\)\s*{([\s\S]*)}$/)
  43.  
  44. assert.ok(match, "Couldn't explode function!")
  45.  
  46. var name = match[1]
  47. , args = match[2]
  48. , body = match[3]
  49.  
  50. return { name:name, args:args, body:body }
  51. }
  52. }
Add Comment
Please, Sign In to add comment