Created
March 25, 2015 02:36
-
-
Save Gwash3189/784f58cc52a8035d622b to your computer and use it in GitHub Desktop.
biker
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
var biker = { | |
parse: function(template) { | |
var rightCurly = "{"; | |
var leftCurly = "}"; | |
var cleanArray = function(x) { | |
return x; | |
}; | |
var splitLeftCurly = function(x) { | |
var s = x.split(leftCurly)[0]; | |
return s; | |
}; | |
var dynamicSegments = template.split(rightCurly) | |
.map(splitLeftCurly) | |
.filter(cleanArray) | |
.map(biker.dynamicSegment); | |
return function(context) { | |
debugger; | |
dynamicSegments = dynamicSegments.map(getValueFromContext).map(parseFunctions); | |
return constructView(dynamicSegments, template); | |
function constructView(dynamicSegments, template) { | |
dynamicSegments.forEach(function(dynamicSegment) { | |
template = template.replace(rightCurly + dynamicSegment.templateValue + leftCurly, dynamicSegment.parseValue); | |
}); | |
return template; | |
} | |
function parseFunctions(dynamicSegment){ | |
debugger; | |
if(isNotParsed(dynamicSegment) && isFunction(dynamicSegment)){ | |
dynamicSegment.parseValue = context[dynamicSegment.templateValue.replace("#","")].bind(context)() || ""; | |
dynamicSegment.parsed = true; | |
} | |
} | |
function getValueFromContext(dynamicSegment) { | |
if(isNotParsed(dynamicSegment) && isNotFunction(dynamicSegment)){ | |
dynamicSegment.parseValue = context[dynamicSegment.templateValue] || ""; | |
dynamicSegment.parsed = true; | |
} | |
return dynamicSegment; | |
} | |
function last(arr) { | |
return arr[arr.length - 1]; | |
} | |
function isNotParsed(segment){ | |
return segment.parsed; | |
} | |
function isFunction(segment){ | |
return segment.templateValue.indexOf("#") === 0; | |
} | |
function isNotFunction(segment){ | |
return !isFunction(segment); | |
} | |
}; | |
}, | |
dynamicSegment: function(s) { | |
return { | |
templateValue: s, | |
parseValue: "", | |
parsed: false | |
}; | |
} | |
}; | |
console.log(biker.parse("<h1>{title}</h1><h2>#thing</h2>")({ | |
title: "It Works!", | |
thing: function(){return "Thing!";} | |
})); | |
//"".split("{").map(function(x){var s = x.split("}")[0]; return s;}).filter(function(x){return x;}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment