-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon-utils.js
93 lines (84 loc) · 2.45 KB
/
common-utils.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
87
88
89
90
91
92
93
/**
* @namespace
*/
sahagin = {};
sahagin.CommonUtils = {};
/**
* @returns {string}
*/
sahagin.CommonUtils.formatVersion = function() {
return "0.9.2";
};
/**
* copied from goog.inherits.
* see http://docs.closure-library.googlecode.com/git/namespace_goog.html
*/
sahagin.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
childCtor.base = function(me, methodName, var_args) {
var args = Array.prototype.slice.call(arguments, 2);
return parentCtor.prototype[methodName].apply(me, args);
};
};
/**
* copied from goog.base.
* see http://docs.closure-library.googlecode.com/git/namespace_goog.html
*/
sahagin.base = function(me, opt_methodName, var_args) {
var caller = arguments.callee.caller;
if (caller.superClass_) {
// This is a constructor. Call the superclass constructor.
return caller.superClass_.constructor.apply(
me, Array.prototype.slice.call(arguments, 1));
}
var args = Array.prototype.slice.call(arguments, 2);
var foundCaller = false;
for (var ctor = me.constructor;
ctor; ctor = ctor.superClass_ && ctor.superClass_.constructor) {
if (ctor.prototype[opt_methodName] === caller) {
foundCaller = true;
} else if (foundCaller) {
return ctor.prototype[opt_methodName].apply(me, args);
}
}
if (me[opt_methodName] === caller) {
return me.constructor.prototype[opt_methodName].apply(me, args);
} else {
throw Error(
'sahagin.base called from a method of one name ' +
'to a method of a different name');
}
};
/**
* @param {string} format
* @param {...*} args
* @returns {string}
*/
sahagin.CommonUtils.strFormat = function(format, args) {
if (!format) {
return format;
}
// use arguments to get all optional arguments
var formatArgs = arguments;
return format.replace(/{(\d+)}/g, function(match, number) {
return formatArgs[parseInt(number) + 1];
});
};
/**
* @param {string} str
* @param {string} pattern
* @returns {boolean} true if str starts with pattern
*/
sahagin.CommonUtils.startsWith = function(str, pattern) {
if (pattern == null || pattern == "" || pattern == undefined) {
throw new Error("invalid pattern: " + pattern);
}
if (str == null || str == undefined) {
return false;
}
return (str.lastIndexOf(pattern, 0) == 0);
};