]> git.wh0rd.org - tt-rss.git/blame - lib/dojo/_base/lang.js
upgrade Dojo to 1.6.1
[tt-rss.git] / lib / dojo / _base / lang.js
CommitLineData
2f01fe57 1/*
81bea17a 2 Copyright (c) 2004-2011, The Dojo Foundation All Rights Reserved.
2f01fe57
AD
3 Available via Academic Free License >= 2.1 OR the modified BSD license.
4 see: http://dojotoolkit.org/license for details
5*/
6
7
a089699c
AD
8if(!dojo._hasResource["dojo._base.lang"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
9dojo._hasResource["dojo._base.lang"] = true;
2f01fe57 10dojo.provide("dojo._base.lang");
a089699c 11
81bea17a 12
2f01fe57 13(function(){
a089699c
AD
14 var d = dojo, opts = Object.prototype.toString;
15
16 // Crockford (ish) functions
17
18 dojo.isString = function(/*anything*/ it){
19 // summary:
20 // Return true if it is a String
21 return (typeof it == "string" || it instanceof String); // Boolean
81bea17a 22 };
a089699c
AD
23
24 dojo.isArray = function(/*anything*/ it){
25 // summary:
26 // Return true if it is an Array.
27 // Does not work on Arrays created in other windows.
28 return it && (it instanceof Array || typeof it == "array"); // Boolean
81bea17a 29 };
a089699c
AD
30
31 dojo.isFunction = function(/*anything*/ it){
32 // summary:
33 // Return true if it is a Function
34 return opts.call(it) === "[object Function]";
35 };
36
37 dojo.isObject = function(/*anything*/ it){
38 // summary:
39 // Returns true if it is a JavaScript object (or an Array, a Function
40 // or null)
41 return it !== undefined &&
42 (it === null || typeof it == "object" || d.isArray(it) || d.isFunction(it)); // Boolean
81bea17a 43 };
a089699c
AD
44
45 dojo.isArrayLike = function(/*anything*/ it){
46 // summary:
47 // similar to dojo.isArray() but more permissive
48 // description:
49 // Doesn't strongly test for "arrayness". Instead, settles for "isn't
50 // a string or number and has a length property". Arguments objects
51 // and DOM collections will return true when passed to
52 // dojo.isArrayLike(), but will return false when passed to
53 // dojo.isArray().
54 // returns:
55 // If it walks like a duck and quacks like a duck, return `true`
56 return it && it !== undefined && // Boolean
57 // keep out built-in constructors (Number, String, ...) which have length
58 // properties
59 !d.isString(it) && !d.isFunction(it) &&
60 !(it.tagName && it.tagName.toLowerCase() == 'form') &&
61 (d.isArray(it) || isFinite(it.length));
81bea17a 62 };
a089699c
AD
63
64 dojo.isAlien = function(/*anything*/ it){
65 // summary:
66 // Returns true if it is a built-in function or some other kind of
67 // oddball that *should* report as a function but doesn't
68 return it && !d.isFunction(it) && /\{\s*\[native code\]\s*\}/.test(String(it)); // Boolean
81bea17a 69 };
a089699c
AD
70
71 dojo.extend = function(/*Object*/ constructor, /*Object...*/ props){
72 // summary:
73 // Adds all properties and methods of props to constructor's
74 // prototype, making them available to all instances created with
75 // constructor.
76 for(var i=1, l=arguments.length; i<l; i++){
77 d._mixin(constructor.prototype, arguments[i]);
78 }
79 return constructor; // Object
81bea17a 80 };
a089699c
AD
81
82 dojo._hitchArgs = function(scope, method /*,...*/){
83 var pre = d._toArray(arguments, 2);
84 var named = d.isString(method);
85 return function(){
86 // arrayify arguments
87 var args = d._toArray(arguments);
88 // locate our method
89 var f = named ? (scope||d.global)[method] : method;
90 // invoke with collected args
91 return f && f.apply(scope || this, pre.concat(args)); // mixed
81bea17a
AD
92 }; // Function
93 };
a089699c
AD
94
95 dojo.hitch = function(/*Object*/scope, /*Function|String*/method /*,...*/){
96 // summary:
97 // Returns a function that will only ever execute in the a given scope.
98 // This allows for easy use of object member functions
99 // in callbacks and other places in which the "this" keyword may
100 // otherwise not reference the expected scope.
81bea17a 101 // Any number of default positional arguments may be passed as parameters
a089699c
AD
102 // beyond "method".
103 // Each of these values will be used to "placehold" (similar to curry)
104 // for the hitched function.
105 // scope:
106 // The scope to use when method executes. If method is a string,
107 // scope is also the object containing method.
108 // method:
109 // A function to be hitched to scope, or the name of the method in
110 // scope to be hitched.
111 // example:
112 // | dojo.hitch(foo, "bar")();
113 // runs foo.bar() in the scope of foo
114 // example:
115 // | dojo.hitch(foo, myFunction);
116 // returns a function that runs myFunction in the scope of foo
117 // example:
118 // Expansion on the default positional arguments passed along from
119 // hitch. Passed args are mixed first, additional args after.
120 // | var foo = { bar: function(a, b, c){ console.log(a, b, c); } };
121 // | var fn = dojo.hitch(foo, "bar", 1, 2);
122 // | fn(3); // logs "1, 2, 3"
123 // example:
124 // | var foo = { bar: 2 };
125 // | dojo.hitch(foo, function(){ this.bar = 10; })();
126 // execute an anonymous function in scope of foo
127
128 if(arguments.length > 2){
129 return d._hitchArgs.apply(d, arguments); // Function
130 }
131 if(!method){
132 method = scope;
133 scope = null;
134 }
135 if(d.isString(method)){
136 scope = scope || d.global;
137 if(!scope[method]){ throw(['dojo.hitch: scope["', method, '"] is null (scope="', scope, '")'].join('')); }
138 return function(){ return scope[method].apply(scope, arguments || []); }; // Function
139 }
140 return !scope ? method : function(){ return method.apply(scope, arguments || []); }; // Function
81bea17a 141 };
a089699c
AD
142
143 /*=====
144 dojo.delegate = function(obj, props){
145 // summary:
146 // Returns a new object which "looks" to obj for properties which it
147 // does not have a value for. Optionally takes a bag of properties to
148 // seed the returned object with initially.
149 // description:
150 // This is a small implementaton of the Boodman/Crockford delegation
151 // pattern in JavaScript. An intermediate object constructor mediates
152 // the prototype chain for the returned object, using it to delegate
153 // down to obj for property lookup when object-local lookup fails.
154 // This can be thought of similarly to ES4's "wrap", save that it does
155 // not act on types but rather on pure objects.
156 // obj:
157 // The object to delegate to for properties not found directly on the
158 // return object or in props.
159 // props:
160 // an object containing properties to assign to the returned object
161 // returns:
162 // an Object of anonymous type
163 // example:
164 // | var foo = { bar: "baz" };
165 // | var thinger = dojo.delegate(foo, { thud: "xyzzy"});
166 // | thinger.bar == "baz"; // delegated to foo
167 // | foo.thud == undefined; // by definition
168 // | thinger.thud == "xyzzy"; // mixed in from props
169 // | foo.bar = "thonk";
170 // | thinger.bar == "thonk"; // still delegated to foo's bar
171 }
172 =====*/
173
174 dojo.delegate = dojo._delegate = (function(){
175 // boodman/crockford delegation w/ cornford optimization
176 function TMP(){}
177 return function(obj, props){
178 TMP.prototype = obj;
179 var tmp = new TMP();
180 TMP.prototype = null;
181 if(props){
182 d._mixin(tmp, props);
183 }
184 return tmp; // Object
81bea17a 185 };
a089699c
AD
186 })();
187
188 /*=====
189 dojo._toArray = function(obj, offset, startWith){
190 // summary:
191 // Converts an array-like object (i.e. arguments, DOMCollection) to an
192 // array. Returns a new Array with the elements of obj.
193 // obj: Object
194 // the object to "arrayify". We expect the object to have, at a
195 // minimum, a length property which corresponds to integer-indexed
196 // properties.
197 // offset: Number?
198 // the location in obj to start iterating from. Defaults to 0.
199 // Optional.
200 // startWith: Array?
201 // An array to pack with the properties of obj. If provided,
202 // properties in obj are appended at the end of startWith and
203 // startWith is the returned array.
204 }
205 =====*/
206
207 var efficient = function(obj, offset, startWith){
208 return (startWith||[]).concat(Array.prototype.slice.call(obj, offset||0));
209 };
210
211 var slow = function(obj, offset, startWith){
212 var arr = startWith||[];
213 for(var x = offset || 0; x < obj.length; x++){
214 arr.push(obj[x]);
215 }
216 return arr;
217 };
218
219 dojo._toArray =
220 d.isIE ? function(obj){
221 return ((obj.item) ? slow : efficient).apply(this, arguments);
222 } :
223 efficient;
224
225 dojo.partial = function(/*Function|String*/method /*, ...*/){
226 // summary:
227 // similar to hitch() except that the scope object is left to be
228 // whatever the execution context eventually becomes.
229 // description:
230 // Calling dojo.partial is the functional equivalent of calling:
231 // | dojo.hitch(null, funcName, ...);
232 var arr = [ null ];
233 return d.hitch.apply(d, arr.concat(d._toArray(arguments))); // Function
81bea17a 234 };
a089699c
AD
235
236 var extraNames = d._extraNames, extraLen = extraNames.length, empty = {};
237
238 dojo.clone = function(/*anything*/ o){
239 // summary:
240 // Clones objects (including DOM nodes) and all children.
241 // Warning: do not clone cyclic structures.
242 if(!o || typeof o != "object" || d.isFunction(o)){
243 // null, undefined, any non-object, or function
244 return o; // anything
245 }
246 if(o.nodeType && "cloneNode" in o){
247 // DOM Node
248 return o.cloneNode(true); // Node
249 }
250 if(o instanceof Date){
251 // Date
252 return new Date(o.getTime()); // Date
253 }
81bea17a
AD
254 if(o instanceof RegExp){
255 // RegExp
256 return new RegExp(o); // RegExp
257 }
a089699c
AD
258 var r, i, l, s, name;
259 if(d.isArray(o)){
260 // array
261 r = [];
262 for(i = 0, l = o.length; i < l; ++i){
263 if(i in o){
264 r.push(d.clone(o[i]));
265 }
266 }
267// we don't clone functions for performance reasons
268// }else if(d.isFunction(o)){
269// // function
270// r = function(){ return o.apply(this, arguments); };
271 }else{
272 // generic objects
273 r = o.constructor ? new o.constructor() : {};
274 }
275 for(name in o){
276 // the "tobj" condition avoid copying properties in "source"
277 // inherited from Object.prototype. For example, if target has a custom
278 // toString() method, don't overwrite it with the toString() method
279 // that source inherited from Object.prototype
280 s = o[name];
281 if(!(name in r) || (r[name] !== s && (!(name in empty) || empty[name] !== s))){
282 r[name] = d.clone(s);
283 }
284 }
285 // IE doesn't recognize some custom functions in for..in
286 if(extraLen){
287 for(i = 0; i < extraLen; ++i){
288 name = extraNames[i];
289 s = o[name];
290 if(!(name in r) || (r[name] !== s && (!(name in empty) || empty[name] !== s))){
291 r[name] = s; // functions only, we don't clone them
292 }
293 }
294 }
295 return r; // Object
81bea17a 296 };
a089699c
AD
297
298 /*=====
299 dojo.trim = function(str){
300 // summary:
301 // Trims whitespace from both sides of the string
302 // str: String
303 // String to be trimmed
304 // returns: String
305 // Returns the trimmed string
306 // description:
307 // This version of trim() was selected for inclusion into the base due
308 // to its compact size and relatively good performance
309 // (see [Steven Levithan's blog](http://blog.stevenlevithan.com/archives/faster-trim-javascript)
310 // Uses String.prototype.trim instead, if available.
311 // The fastest but longest version of this function is located at
312 // dojo.string.trim()
313 return ""; // String
314 }
315 =====*/
316
317 dojo.trim = String.prototype.trim ?
318 function(str){ return str.trim(); } :
319 function(str){ return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); };
320
321 /*=====
322 dojo.replace = function(tmpl, map, pattern){
323 // summary:
324 // Performs parameterized substitutions on a string. Throws an
81bea17a 325 // exception if any parameter is unmatched.
a089699c
AD
326 // tmpl: String
327 // String to be used as a template.
328 // map: Object|Function
329 // If an object, it is used as a dictionary to look up substitutions.
330 // If a function, it is called for every substitution with following
331 // parameters: a whole match, a name, an offset, and the whole template
332 // string (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/String/replace
333 // for more details).
334 // pattern: RegEx?
335 // Optional regular expression objects that overrides the default pattern.
336 // Must be global and match one item. The default is: /\{([^\}]+)\}/g,
337 // which matches patterns like that: "{xxx}", where "xxx" is any sequence
338 // of characters, which doesn't include "}".
339 // returns: String
340 // Returns the substituted string.
341 // example:
342 // | // uses a dictionary for substitutions:
343 // | dojo.replace("Hello, {name.first} {name.last} AKA {nick}!",
344 // | {
345 // | nick: "Bob",
346 // | name: {
347 // | first: "Robert",
348 // | middle: "X",
349 // | last: "Cringely"
350 // | }
351 // | });
352 // | // returns: Hello, Robert Cringely AKA Bob!
353 // example:
354 // | // uses an array for substitutions:
355 // | dojo.replace("Hello, {0} {2}!",
356 // | ["Robert", "X", "Cringely"]);
357 // | // returns: Hello, Robert Cringely!
358 // example:
359 // | // uses a function for substitutions:
360 // | function sum(a){
361 // | var t = 0;
362 // | dojo.forEach(a, function(x){ t += x; });
363 // | return t;
364 // | }
365 // | dojo.replace(
366 // | "{count} payments averaging {avg} USD per payment.",
367 // | dojo.hitch(
368 // | { payments: [11, 16, 12] },
369 // | function(_, key){
370 // | switch(key){
371 // | case "count": return this.payments.length;
372 // | case "min": return Math.min.apply(Math, this.payments);
373 // | case "max": return Math.max.apply(Math, this.payments);
374 // | case "sum": return sum(this.payments);
375 // | case "avg": return sum(this.payments) / this.payments.length;
376 // | }
377 // | }
378 // | )
379 // | );
380 // | // prints: 3 payments averaging 13 USD per payment.
381 // example:
382 // | // uses an alternative PHP-like pattern for substitutions:
383 // | dojo.replace("Hello, ${0} ${2}!",
384 // | ["Robert", "X", "Cringely"], /\$\{([^\}]+)\}/g);
385 // | // returns: Hello, Robert Cringely!
386 return ""; // String
387 }
388 =====*/
389
390 var _pattern = /\{([^\}]+)\}/g;
391 dojo.replace = function(tmpl, map, pattern){
392 return tmpl.replace(pattern || _pattern, d.isFunction(map) ?
393 map : function(_, k){ return d.getObject(k, false, map); });
394 };
2f01fe57 395})();
a089699c 396
2f01fe57 397}