Created
December 3, 2013 23:33
-
-
Save ThomasBurleson/7779666 to your computer and use it in GitHub Desktop.
String building function that support index-based or key-based token substitutions; e.g. supplant( "Hello {firstName} {lastName}", user );
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
# Make sure the supplant() method is available! | |
# Now supports dot notation for complex object value substitutions | |
# e.e. {foo.boo.moo.uff ...} | |
String::supplant = (o) -> | |
this.replace /\{([^{}]*)\}/g, (a, b) -> | |
p = b.split('.') | |
r = o | |
# Descend the property chain "b" to resolve the end-chain value | |
try | |
for own s of p | |
r = r[p[s]] | |
catch e | |
r = a | |
return if (r is 'string') or (r is 'number') then r else a | |
# return `(r === 'string') || (r ==='number') ? r : a` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Here is the JavaScript version: