Skip to content

Instantly share code, notes, and snippets.

@spiralx
Created February 24, 2015 13:51
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 spiralx/7c21b5cc1d686259c12a to your computer and use it in GitHub Desktop.
Save spiralx/7c21b5cc1d686259c12a to your computer and use it in GitHub Desktop.
Various small utility functions for user scripts
;(function(name, definition) {
var moduleObj = definition();
// AMD Module
if (typeof define === 'function') {
define(moduleObj);
}
// CommonJS Module
else if (typeof module !== 'undefined' && module.exports) {
module.exports = moduleObj;
}
// Assign to the global object (window)
else {
this[name] = moduleObj;
}
})('utils', function() {
'use strict';
return {
/**
* Simple string substution function.
*
* fmt('x={0}, y={1}', 12, 4) -> 'x=12, y=4'
* fmt('x={x}, y={y}', { x: 12, y: 4 }) -> 'x=12, y=4'
* fmt('x={x}, y={{moo}}', { x: 12, y: 4 }) -> 'x=12, y={moo}'
* fmt('{x}: {y.thing}', { x: 'foo', y: { thing: 'bar' }}) -> 'foo: bar'
* fmt('{x}: {y.a[1]}', { x: 'foo', y: { thing: 'bar', a: [6, 7] }}) -> 'foo: 7'
* fmt('{0[2]}, {0[-2]}', [{ x: 12, y: 4 }, 7, 120, 777, 999]) -> '120, 777'
* fmt('{0[-5].y}', [{ x: 12, y: 4 }, 7, 120, 777, 999]) -> '4'
* fmt('{a[-5].x}', {a: [{ x: 12, y: 4 }, 7, 120, 777, 999]}) -> '12'
*
* @param {String} format
* @param {Object|Object+} data
* @return {String}
*/
format: function(formatString, data) {
data = arguments.length == 2 && typeof data === "object" && !Array.isArray(data)
? data
: [].slice.call(arguments, 1);
return formatString
.replace(/\{\{/g, String.fromCharCode(0))
.replace(/\}\}/g, String.fromCharCode(1))
.replace(/\{([^}]+)\}/g, function(match, path) {
try {
var p = path.replace(/\[(-?\w+)\]/g, '.$1').split('.');
//console.log('path="%s" (%s), data=%s', path, p.toSource(), data.toSource());
return String(p.reduce(function(o, n) {
return o.slice && !isNaN(n) ? o.slice(n).shift() : o[n];
}, data));
}
catch (ex) {
return match;
}
})
.replace(/\x00/g, "{")
.replace(/\x01/g, "}");
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment