Formulation of the problem
Quite by chance, I turned from a pythonist into a JS developer, and an overwhelming burden of things that are not in JS fell upon my fragile children's psyche. For example, there is no convenient formatting of strings. On python, you can write:
'hello, %(thing)s' % {'thing': 'world'}
Or like this:
'hello, {thing}'.format(**{'thing': 'world'})

The closest analogue in JS is concatenation (
operator +
), which scales very poorly with increasing string length, and it even looks ugly to the limit:
'<div class="input-append"><input type="text" name="username" '+ 'id="signup_username" placeholder="'+placeholder+'"><input '+ 'type="hidden" name="password" value="'+generated+'"><button '+ ...
If possible, I would like to avoid this.
Jeremy Ashkenas, when developing CoffeeScript, also paid attention to this feature of JS, and accidentally the PHP dialect:
"hello, #{document.cookie}"
This is also bad, besides, it works only for string literals, it will not work to load a template from a file.
I like the Ruby-like syntax in this thing, but I don’t like everything else, especially the execution of arbitrary code within a string. Thus, the statement of the problem:
- write function
- which substitutes variables in the string
- loaded from file
- not PHP
Finding a solution
Usually, in such cases, ready-made libraries are used, moreover, in NPM, according to the word template, there are more than two thousand packages.
')
In fact, mustache or lodash (underscore.js) work perfectly, but ... very slowly: 10-20 microsec per one substitution. Not the ultimate dream in any case, especially when the "advanced" functionality like cycles and filters is absolutely not needed.
And the concatenation, although it looks scary, like an animal grin of collectivism, still works 10-30 times faster. Thus, we add to the problem statement:
- translated into concatenation
- and it works very fast
Now, according to this specification, you can reinvent the wheel. Because why not.
What happened
I got this thing:
Ruby-like simple string interpolation (GitHub)It contains 9 lines of code, and it performs one million three hundred thousand substitutions per second (about 0.77 μs per substitution) on the same machine where mustache makes 130 thousand, and lodash / underscore 45 thousand substitutions per second.
var hello = fmt('hello, #{thing}') hello({thing: 'world'})
Conclusion: due to the rejection of the complex functions of the template (cycles, conditional expressions), acceleration was achieved 10-30 times in comparison with popular libraries, without resorting to the execution of arbitrary code in the template.
Rssi.js can be installed from npm by the obvious
npm install rssi
, Bower is also supported (
bower install rssi
); On the client side, you can use AMD (RequireJS), but you can not use it.

Thanks for reading this not very coherent text! Write patches, gentlemen, good, and see you soon.