Skip to content

Instantly share code, notes, and snippets.

@astroza
Created May 25, 2017 01:43
Show Gist options
  • Save astroza/059c468b7638f283f0ca8b2dd9e4687a to your computer and use it in GitHub Desktop.
Save astroza/059c468b7638f283f0ca8b2dd9e4687a to your computer and use it in GitHub Desktop.
// fastroza (TM)
// Comments about https://mobile.twitter.com/lukaseder/status/867080556470730752
var js_behavior = false
function add(_x, _y) { // (x) + (b)
// Normalization to Number
var x = +_x
var y = +_y
if(!js_behavior)
return x+y
// How JS interp works
if(typeof _x == 'string' || typeof _y == 'string')
return _x.toString().concat(_y.toString())
return x+y
}
function sub(_x, _y) { // (x) - (b)
// Normalization to Number
var x = +_x
var y = +_y
if(!js_behavior)
return x-y
// How JS interp works
return x-y
}
function unary_add(x) { // + (x)
return Number(x)
}
function unary_sub(x) { // - (x)
return unary_add(x)
}
function test(exp) {
console.log(exp + "=" + eval(exp))
}
js_behavior = false
console.log("\njs_behavior = false\n")
test("sub('5', 3)") // '5' - 3
test("add('5', 3)") // '5' + 3
test("sub('5', '4')") // '5' - '4'
test("add('5', unary_add('5'))") // '5' + + '5'
test("add('foo', unary_add('foo'))") // 'foo' + + 'foo'
var x = 3
test("sub(add('5', x), x)") // '5' + x - x, it builds AST from left to right, no priorities here
test("add(sub('5', x), x)") // '5' - x + x, it builds AST from left to right, no priorities here
js_behavior = true
console.log("\njs_behavior = true\n")
test("sub('5', 3)") // '5' - 3
test("add('5', 3)") // '5' + 3
test("sub('5', '4')") // '5' - '4'
test("add('5', unary_add('5'))") // '5' + + '5'
test("add('foo', unary_add('foo'))") // 'foo' + + 'foo'
var x = 3
test("sub(add('5', x), x)") // '5' + x - x, it builds AST from left to right, no priorities here
test("add(sub('5', x), x)") // '5' - x + x, it builds AST from left to right, no priorities here
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment