ember-intl
Version:
Ember toolbox for internationalization.
79 lines (56 loc) • 1.75 kB
JavaScript
/*
Copyright (c) 2014, Yahoo! Inc. All rights reserved.
Copyrights licensed under the New BSD License.
See the accompanying LICENSE file for terms.
*/
/* jshint esnext: true */
// -----------------------------------------------------------------------------
function orderedProps(obj) {
var props = [], keys = [];
var key, i, len, prop;
for (key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
var orderedKeys = keys.sort();
for (i = 0, len = orderedKeys.length; i < len; i += 1) {
key = orderedKeys[i];
prop = {};
prop[key] = obj[key];
props[i] = prop;
}
return props;
}
function getCacheId(inputs) {
// When JSON is not available in the runtime, we will not create a cache id.
if (typeof JSON === 'undefined') { return; }
var cacheId = [];
var i, len, input;
for (i = 0, len = inputs.length; i < len; i += 1) {
input = inputs[i];
if (input && typeof input === 'object') {
cacheId.push(orderedProps(input));
} else {
cacheId.push(input);
}
}
return JSON.stringify(cacheId);
}
function createFormatCache(FormatConstructor) {
var cache = Object.create(null);
return function () {
var args = Array.prototype.slice.call(arguments);
var cacheId = getCacheId(args);
var format = cacheId && cache[cacheId];
if (!format) {
format = Object.create(FormatConstructor.prototype);
FormatConstructor.apply(format, args);
if (cacheId) {
cache[cacheId] = format;
}
}
return format;
};
}
export default createFormatCache;