Last active
August 29, 2015 14:17
-
-
Save ewebdev/68d4e1dcabc3d7cacae5 to your computer and use it in GitHub Desktop.
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
function compile (pattern, mapping) { | |
pattern = pattern || ''; | |
var i, | |
ch, | |
last, | |
attrName, | |
sequenceLength = 0, | |
len = pattern.length, | |
builder = [], | |
attrsCharsMapping = {}, | |
isUpper. | |
shouldAppend; | |
for (attrName in mapping) { | |
if (mapping.hasOwnProperty(attrName)) { | |
attrsCharsMapping[attrName.toLowerCase()] = attrsCharsMapping[attrName.toUpperCase()] = mapping[attrName]; | |
} | |
} | |
last = pattern[0]; | |
for (i = 0; i <= len; i++) { | |
ch = pattern[i]; | |
attrName = attrsCharsMapping[last]; | |
isUpper = (last || '').toUpperCase() === last; | |
shouldAppend = !attrName || (i > 0 && isUpper || ch !== last); | |
if (shouldAppend) { | |
if (attrName) { | |
builder.push('(attrs.' + attrName + " || '')" + (isUpper ? '' : '.substr(0,' + sequenceLength + ')')); | |
} else { | |
builder.push("'" + last + "'"); | |
} | |
sequenceLength = 1; | |
} else { | |
sequenceLength++; | |
} | |
last = ch; | |
} | |
var fnBody = 'return ' + builder.join(' + ') + ';'; | |
return new Function('attrs', fnBody) | |
}; | |
///* EXAMPLE USAGE */ | |
// var template = compile('Fl@D', {f: 'firstName', l: 'lastName', d: 'domain'}); | |
// template ({firstName: 'Eyal', lastName: 'Weiss', domain: 'similartech.com'}); | |
// template ({firstName: 'John', lastName: 'Doe', domain: 'domain.com'}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment