forked from evil1-2/adarkroom
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translate.js
86 lines (70 loc) · 1.61 KB
/
translate.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
(function() {
var translate = function(text)
{
var xlate = translateLookup(text);
if (typeof xlate == "function")
{
xlate = xlate.apply(this, arguments);
}
else if (arguments.length > 1)
{
var aps = Array.prototype.slice;
var args = aps.call( arguments, 1 );
xlate = formatter(xlate, args);
}
return xlate;
};
// I want it available explicity as well as via the object
translate.translate = translate;
//from https://gist.github.com/776196 via http://davedash.com/2010/11/19/pythonic-string-formatting-in-javascript/
var defaultFormatter = (function() {
var re = /\{([^}]+)\}/g;
return function(s, args) {
return s.replace(re, function(_, match){ return args[match]; });
};
}());
var formatter = defaultFormatter;
translate.setFormatter = function(newFormatter)
{
formatter = newFormatter;
};
translate.format = function()
{
var aps = Array.prototype.slice;
var s = arguments[0];
var args = aps.call( arguments, 1 );
return formatter(s, args);
};
var dynoTrans = null;
translate.setDynamicTranslator = function(newDynoTrans)
{
dynoTrans = newDynoTrans;
};
var translation = null;
translate.setTranslation = function(newTranslation)
{
translation = newTranslation;
};
function translateLookup(target)
{
if (translation == null || target == null)
{
return target;
}
if (target in translation === false)
{
if (dynoTrans != null)
{
return dynoTrans(target);
}
return target;
}
var result = translation[target];
if (result == null)
{
return target;
}
return result;
}
window._ = translate;
})();