Created
June 26, 2016 17:17
-
-
Save burakcan/cd57815c3662e5803936958bf9408d63 to your computer and use it in GitHub Desktop.
Basic F# forward / backward operators in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* jshint esnext: true */ | |
const FORWARD = '|>'; | |
const BACKWARD = '<|'; | |
function _(...args) { | |
return function(value) { | |
return args.reduce((val, curr, index) => { | |
switch(curr) { | |
case FORWARD: | |
return args[index + 1](val); | |
case BACKWARD: | |
return val(args[index + 1]); | |
default: | |
return val; | |
} | |
}, value); | |
}; | |
} | |
const pipeline = _( | |
'|>', map(_( | |
'|>', add, '<|', 1 | |
)), | |
'|>', concat, '<|', ['a', 'b', 'c'], | |
'|>', join, | |
'|>', remove, '<|', (/,/g) | |
); | |
const otherPipeline = _( | |
'|>', split, '<|', '' | |
); | |
const result = pipeline([1, 2, 3]); | |
const otherResult = otherPipeline(result); | |
console.log(result); | |
console.log(otherResult); | |
function add(num) { | |
return function(val) { | |
return val + num; | |
}; | |
} | |
function map(fn) { | |
return function(arr) { | |
return arr.map(fn); | |
}; | |
} | |
function join(arr) { | |
return arr.join(); | |
} | |
function split(str) { | |
return function(val) { | |
return str.split(val); | |
}; | |
} | |
function concat(one) { | |
return function(two) { | |
return one.concat(two); | |
}; | |
} | |
function remove(str) { | |
return function(reg) { | |
return str.replace(reg, ''); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment