Skip to content

Instantly share code, notes, and snippets.

@chrispsn
Created August 20, 2019 09:09
Show Gist options
  • Save chrispsn/06990a21bd476bd44e3e40a1a6cc1b34 to your computer and use it in GitHub Desktop.
Save chrispsn/06990a21bd476bd44e3e40a1a6cc1b34 to your computer and use it in GitHub Desktop.
Exercise in writing compressed JavaScript using b-like techniques
// Inspired by http://kparc.com/b/c.h
// See also https://chat.stackexchange.com/transcript/message/51402407#51402407
const x="x",y="y"
// Function makers
function fn() {return new Function(...arguments)}
function f0(b) {return fn(b)}
function f1(b) {return fn(x,b)}
function f2(b) {return fn(x,y,b)}
function run(b) {f0(b)()}
// Strings
const
R = f1("return 'return '+x"),
P = f1(R("'console.log(\"'+x+'\")'")),
DO = f2(R("'for(var i=0,_l='+x+';i<_l;i++){'+y+'}'")),
LEN = f1(R("x+'.length'")),
OVER = f2("var a=0;"+DO(LEN(y),"a=x(a,y[i])")+R("a")), // replace with 'reduce'?
SCAN = f2("var a=0,r=[];"+DO(LEN(y),"r.push(a=x(a,y[i]))")+R("r")),
ADD = f2(R("x+y")),
MAX = f2(R("Math.max(x,y)")) // pointer to max not stored...
// Yes, map/reduce array methods would do a lot of this...
run(DO(3,P("hello"))) // 3x 'hello'
run(P(f1(R("x+1"))(1))) // 2
run(P(OVER(ADD,[1,2,3]))) // 6
run(P(SCAN(ADD,[1,2,3]))) // [1,3,6]
run(P(OVER(MAX,[2,3,1]))) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment