Skip to content

Instantly share code, notes, and snippets.

@piecyk
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save piecyk/71f94f51408220f016a6 to your computer and use it in GitHub Desktop.

Select an option

Save piecyk/71f94f51408220f016a6 to your computer and use it in GitHub Desktop.
filter('translate', function (SOME_SERVICE) {
return function (key, args) {
function formatString(str) {
if(!str) {return ""};
var args = Array.prototype.slice.call(arguments, 1),
rgx = /{(\d+)}/g;
if(!args.length) return str;
return str.replace(rgx, function(match, number) {
return typeof args[number] != 'undefined' ?args[number] : match;
});
}
return formatString.apply(null, [SOME_SERVICE.getText(key)].concat(args));
}
})
efecte.services.service("SOME_SERVICE", ["Service", function (Service) {
var texts = {
"default": {} // Service
};
//returnstext for key, if not found returns key
this.getText = function (key) {
return texts["default"] [key] || key;
};
}]);
describe('translate filter', function () {
var filter;
beforeEach(module('filters'));
var dictionary = {
key: 'value',
key1: 'value1',
key2: 'value2',
keyParam: "Hello {0}!",
keyParams: "A, {0}, {1}, D, {2}, F, {3}",
keyOrder: "2-{1}, 1-{0}, 4-{3}, 3-{2}"
};
it("should be defined", inject(function($filter) {
expect($filter('translate')).toBeDefined();
}));
it("should value string", inject(function($filter) {
expect($filter('translate')("key")).toBe(dictionary.key);
expect($filter('translate')("key1")).toBe(dictionary.key1);
expect($filter('translate')("key2")).toBe(dictionary.key2);
}));
it("should value string with params", inject(function($filter) {
expect($filter('translate')("keyParam", "world" )).toBe("Hello world!");
expect($filter('translate')("keyParams", ["B", "C", "E", "G"])).toBe("A, B, C, D, E, F, G");
expect($filter('translate')("keyOrder", [1, 2, 3, 4])).toBe("2-2, 1-1, 4-4, 3-3");
}));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment