lang.js 13 KB

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