Skip to content

Instantly share code, notes, and snippets.

@anotherxx
Created December 7, 2017 17:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anotherxx/79c782fa46c78bd19718ea8c4bcc2b6f to your computer and use it in GitHub Desktop.
Save anotherxx/79c782fa46c78bd19718ea8c4bcc2b6f to your computer and use it in GitHub Desktop.
Pipe and Reduce implementation
let statement = "wELCOME | lower | capitalize";
let another = "welcome | upper";
let handlers = {
lower : (val) => val.toLowerCase(),
upper: (val) => val.toUpperCase(),
capitalize: (val) => val.slice(0,1).toUpperCase() + val.slice(1)
};
function parseStatement(statement)
{
let pieces = statement.split("|").map(piece => piece.trim())
let needle = pieces.shift();
let result = pieces.reduce((value , handlerName) =>
{
return handlers[handlerName](value);
} , needle);
console.log(result);
}
parseStatement(statement);
parseStatement(another);
function customReduce(list , handler , initial=false)
{
var len = list.length;
var curResult;
for(var i = 0; i < len; i++)
{
if(initial) {
if(i == 0){
var curResult = handler.call(this , initial , list[i]);
}else {
var curResult = handler.call(this , curResult , list[i]);
}
}else{
if(i == 0) {
var curResult = handler.call(this , list[i] , list[i + 1]);
i += 1;
}
else{
var curResult = handler.call(this, curResult , list[i]);
}
}
}
console.log(curResult);
}
let list = [1,2,3,4,5];
let handler = (a,b) =>
{
return a + b;
};
customReduce(list ,handler , 20);
customReduce(list , handler);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment