Skip to content

Instantly share code, notes, and snippets.

@Sequoia
Created December 10, 2015 19:36
Show Gist options
  • Save Sequoia/4c1d3b07e5a75f73a5de to your computer and use it in GitHub Desktop.
Save Sequoia/4c1d3b07e5a75f73a5de to your computer and use it in GitHub Desktop.
some iterations on a compose function for JS
//stuff shared across many vs of compose
//util
const call = method => (...args) => obj => obj[method](...args);
let l = console.log.bind(console);
///
const compose = require(/*one of them*/);
//fs = [x, y, z];
//return a => x(y(z(a)));
const double = x => 2 * x;
const square = x => x * x;
//tryout
const ds = compose(double,square); //should square then double
const rev = composee(call('reverse')(),call('slice')());
const red = call('reduce');
const join = call('join');
const list = ["a","b","c","d"];
l(rev(list));
l(list);
l(join('<-')(list));
l(compose(join('<-'),rev)(list));
function compose(...fs){
let last = null;
for(let i = fs.length - 1; i >= 0; i--){
let lastFn = last;
let thisFn = fs[i];
if(lastFn === null){
last = thisFn;
}else{
last = x => thisFn(lastFn(x));
}
}
return last;
}
function compose2(...fns){
let fs = fns.reverse();
let last = null;
for(let i = 0; i < fs.length; i++){
let lastFn = last;
let thisFn = fs[i];
if(lastFn === null){
last = thisFn;
}else{
last = x => thisFn(lastFn(x));
}
}
return last;
}
function compose3(...fs){
return fs
.reverse()
.reduce(function(last, cur){
if(last === null){
return cur;
}else{
return x => cur(last(x));
}
},null);
}
function compose4(...fs){
return fs
.reverse()
.reduce(function(last, cur){
return x => cur(last(x));
},x => x);
}
function compose5(...fs){
return fs
.reverse()
.reduce((l,c)=> x => c(l(x)),x => x);
}
const comp6 = (...fs) => red((l,c)=> x => c(l(x)),x => x)(rev(fs))
function comp(...fs){
//let rev, red;
// if(fs.length === 1) return fs[0];
let idk = red((l,c)=> x => c(l(x)),x => x);
//can't quite get it down to 1 fn.
return comp(idk, rev)(fs);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment