after review improvements
[mootools.git] / Source / Core / Core.js
blobd4521d4badb8d03a31086c9d139a6768ab4216c5
1 /*
2 ---
4 name: Core
6 description: The heart of MooTools.
8 license: MIT-style license.
10 copyright: Copyright (c) 2006-2014 [Valerio Proietti](http://mad4milk.net/).
12 authors: The MooTools production team (http://mootools.net/developers/)
14 inspiration:
15   - Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
16   - Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
18 provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
20 ...
22 /*! MooTools: the javascript framework. license: MIT-style license. copyright: Copyright (c) 2006-2014 [Valerio Proietti](http://mad4milk.net/).*/
23 (function(){
25 this.MooTools = {
26         version: '1.5.2-dev',
27         build: '%build%'
30 // typeOf, instanceOf
32 var typeOf = this.typeOf = function(item){
33         if (item == null) return 'null';
34         if (item.$family != null) return item.$family();
36         if (item.nodeName){
37                 if (item.nodeType == 1) return 'element';
38                 if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
39         } else if (typeof item.length == 'number'){
40                 if ('callee' in item) return 'arguments';
41                 if ('item' in item) return 'collection';
42         }
44         return typeof item;
47 var instanceOf = this.instanceOf = function(item, object){
48         if (item == null) return false;
49         var constructor = item.$constructor || item.constructor;
50         while (constructor){
51                 if (constructor === object) return true;
52                 constructor = constructor.parent;
53         }
54         /*<ltIE8>*/
55         if (!item.hasOwnProperty) return false;
56         /*</ltIE8>*/
57         return item instanceof object;
60 /*<ltIE8>*/
61 var enumerables = true;
62 for (var i in {toString: 1}) enumerables = null;
63 if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
64 /*</ltIE8>*/
65 var hasOwnProperty = Object.prototype.hasOwnProperty;
66 function objectKeys(object, alsoPrototypeChain){
67         var keys = [];
68     for (var k in object){
69                 if (alsoPrototypeChain) keys.push(k);
70                 else hasOwnProperty.call(object, k) && keys.push(k);
71         }
72         /*<ltIE8>*/
73         if (enumerables) for (var i = enumerables.length; i--;){
74                 k = enumerables[i];
75                 if (hasOwnProperty.call(object, k)) keys.push(k);
76         }
77         /*</ltIE8>*/
78         return keys;
81 // Function overloading
83 var Function = this.Function;
85 Function.prototype.overloadSetter = function(usePlural){
86         var self = this;
87         return function(a, b){
88                 if (a == null) return this;
89                 if (usePlural || typeof a != 'string'){
90                         var keys = objectKeys(a, true), k;
91                         for (var i = 0; k = keys[i]; i++) self.call(this, k, a[k]);
92                 } else {
93                         self.call(this, a, b);
94                 }
95                 return this;
96         };
99 Function.prototype.overloadGetter = function(usePlural){
100         var self = this;
101         return function(a){
102                 var args, result;
103                 if (typeof a != 'string') args = a;
104                 else if (arguments.length > 1) args = arguments;
105                 else if (usePlural) args = [a];
106                 if (args){
107                         result = {};
108                         for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
109                 } else {
110                         result = self.call(this, a);
111                 }
112                 return result;
113         };
116 Function.prototype.extend = function(key, value){
117         this[key] = value;
118 }.overloadSetter();
120 Function.prototype.implement = function(key, value){
121         this.prototype[key] = value;
122 }.overloadSetter();
124 // From
126 var slice = Array.prototype.slice;
128 Function.from = function(item){
129         return (typeOf(item) == 'function') ? item : function(){
130                 return item;
131         };
134 Array.from = function(item){
135         if (item == null) return [];
136         return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
139 Number.from = function(item){
140         var number = parseFloat(item);
141         return isFinite(number) ? number : null;
144 String.from = function(item){
145         return item + '';
148 // hide, protect
150 Function.implement({
152         hide: function(){
153                 this.$hidden = true;
154                 return this;
155         },
157         protect: function(){
158                 this.$protected = true;
159                 return this;
160         }
164 // Type
166 var Type = this.Type = function(name, object){
167         if (name){
168                 var lower = name.toLowerCase();
169                 var typeCheck = function(item){
170                         return (typeOf(item) == lower);
171                 };
173                 Type['is' + name] = typeCheck;
174                 if (object != null){
175                         object.prototype.$family = (function(){
176                                 return lower;
177                         }).hide();
178                         //<1.2compat>
179                         object.type = typeCheck;
180                         //</1.2compat>
181                 }
182         }
184         if (object == null) return null;
186         object.extend(this);
187         object.$constructor = Type;
188         object.prototype.$constructor = object;
190         return object;
193 var toString = Object.prototype.toString;
195 Type.isEnumerable = function(item){
196         return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
199 var hooks = {};
201 var hooksOf = function(object){
202         var type = typeOf(object.prototype);
203         return hooks[type] || (hooks[type] = []);
206 var implement = function(name, method){
207         if (method && method.$hidden) return;
209         var hooks = hooksOf(this);
211         for (var i = 0; i < hooks.length; i++){
212                 var hook = hooks[i];
213                 if (typeOf(hook) == 'type') implement.call(hook, name, method);
214                 else hook.call(this, name, method);
215         }
217         var previous = this.prototype[name];
218         if (previous == null || !previous.$protected) this.prototype[name] = method;
220         if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
221                 return method.apply(item, slice.call(arguments, 1));
222         });
225 var extend = function(name, method){
226         if (method && method.$hidden) return;
227         var previous = this[name];
228         if (previous == null || !previous.$protected) this[name] = method;
231 Type.implement({
233         implement: implement.overloadSetter(),
235         extend: extend.overloadSetter(),
237         alias: function(name, existing){
238                 implement.call(this, name, this.prototype[existing]);
239         }.overloadSetter(),
241         mirror: function(hook){
242                 hooksOf(this).push(hook);
243                 return this;
244         }
248 new Type('Type', Type);
250 // Default Types
252 var force = function(name, object, methods){
253         var isType = (object != Object),
254                 prototype = object.prototype;
256         if (isType) object = new Type(name, object);
258         for (var i = 0, l = methods.length; i < l; i++){
259                 var key = methods[i],
260                         generic = object[key],
261                         proto = prototype[key];
263                 if (generic) generic.protect();
264                 if (isType && proto) object.implement(key, proto.protect());
265         }
267         if (isType){
268                 var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
269                 object.forEachMethod = function(fn){
270                         if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
271                                 fn.call(prototype, prototype[methods[i]], methods[i]);
272                         }
273                         for (var key in prototype) fn.call(prototype, prototype[key], key);
274                 };
275         }
277         return force;
280 force('String', String, [
281         'charAt', 'charCodeAt', 'concat', 'contains', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
282         'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
283 ])('Array', Array, [
284         'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
285         'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight', 'contains'
286 ])('Number', Number, [
287         'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
288 ])('Function', Function, [
289         'apply', 'call', 'bind'
290 ])('RegExp', RegExp, [
291         'exec', 'test'
292 ])('Object', Object, [
293         'create', 'defineProperty', 'defineProperties', 'keys',
294         'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
295         'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
296 ])('Date', Date, ['now']);
298 Object.extend = extend.overloadSetter();
300 Date.extend('now', function(){
301         return +(new Date);
304 new Type('Boolean', Boolean);
306 // fixes NaN returning as Number
308 Number.prototype.$family = function(){
309         return isFinite(this) ? 'number' : 'null';
310 }.hide();
312 // Number.random
314 Number.extend('random', function(min, max){
315         return Math.floor(Math.random() * (max - min + 1) + min);
318 // forEach, each, keys
320 Array.implement({
322         /*<!ES5>*/
323         forEach: function(fn, bind){
324                 for (var i = 0, l = this.length; i < l; i++){
325                         if (i in this) fn.call(bind, this[i], i, this);
326                 }
327         },
328         /*</!ES5>*/
330         each: function(fn, bind){
331                 Array.forEach(this, fn, bind);
332                 return this;
333         }
337 Object.extend({
339         keys: objectKeys,
341         forEach: function(object, fn, bind){
342                 Object.keys(object).forEach(function(key){
343                         fn.call(bind, object[key], key, object);
344                 });
345         }
349 Object.each = Object.forEach;
352 // Array & Object cloning, Object merging and appending
354 var cloneOf = function(item){
355         switch (typeOf(item)){
356                 case 'array': return item.clone();
357                 case 'object': return Object.clone(item);
358                 default: return item;
359         }
362 Array.implement('clone', function(){
363         var i = this.length, clone = new Array(i);
364         while (i--) clone[i] = cloneOf(this[i]);
365         return clone;
368 var mergeOne = function(source, key, current){
369         switch (typeOf(current)){
370                 case 'object':
371                         if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
372                         else source[key] = Object.clone(current);
373                 break;
374                 case 'array': source[key] = current.clone(); break;
375                 default: source[key] = current;
376         }
377         return source;
380 Object.extend({
382         merge: function(source, k, v){
383                 if (typeOf(k) == 'string') return mergeOne(source, k, v);
384                 for (var i = 1, l = arguments.length; i < l; i++){
385                         var object = arguments[i];
386                         for (var key in object) mergeOne(source, key, object[key]);
387                 }
388                 return source;
389         },
391         clone: function(object){
392                 var clone = {};
393                 for (var key in object) clone[key] = cloneOf(object[key]);
394                 return clone;
395         },
397         append: function(original){
398                 for (var i = 1, l = arguments.length; i < l; i++){
399                         var extended = arguments[i] || {};
400                         for (var key in extended) original[key] = extended[key];
401                 }
402                 return original;
403         }
407 // Object-less types
409 ['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
410         new Type(name);
413 // Unique ID
415 var UID = Date.now();
417 String.extend('uniqueID', function(){
418         return (UID++).toString(36);
421 //<1.2compat>
423 var Hash = this.Hash = new Type('Hash', function(object){
424         if (typeOf(object) == 'hash') object = Object.clone(object.getClean());
425         for (var key in object) this[key] = object[key];
426         return this;
429 Hash.implement({
431         forEach: function(fn, bind){
432                 Object.forEach(this, fn, bind);
433         },
435         getClean: function(){
436                 var clean = {};
437                 for (var key in this){
438                         if (this.hasOwnProperty(key)) clean[key] = this[key];
439                 }
440                 return clean;
441         },
443         getLength: function(){
444                 var length = 0;
445                 for (var key in this){
446                         if (this.hasOwnProperty(key)) length++;
447                 }
448                 return length;
449         }
453 Hash.alias('each', 'forEach');
455 Object.type = Type.isObject;
457 var Native = this.Native = function(properties){
458         return new Type(properties.name, properties.initialize);
461 Native.type = Type.type;
463 Native.implement = function(objects, methods){
464         for (var i = 0; i < objects.length; i++) objects[i].implement(methods);
465         return Native;
468 var arrayType = Array.type;
469 Array.type = function(item){
470         return instanceOf(item, Array) || arrayType(item);
473 this.$A = function(item){
474         return Array.from(item).slice();
477 this.$arguments = function(i){
478         return function(){
479                 return arguments[i];
480         };
483 this.$chk = function(obj){
484         return !!(obj || obj === 0);
487 this.$clear = function(timer){
488         clearTimeout(timer);
489         clearInterval(timer);
490         return null;
493 this.$defined = function(obj){
494         return (obj != null);
497 this.$each = function(iterable, fn, bind){
498         var type = typeOf(iterable);
499         ((type == 'arguments' || type == 'collection' || type == 'array' || type == 'elements') ? Array : Object).each(iterable, fn, bind);
502 this.$empty = function(){};
504 this.$extend = function(original, extended){
505         return Object.append(original, extended);
508 this.$H = function(object){
509         return new Hash(object);
512 this.$merge = function(){
513         var args = Array.slice(arguments);
514         args.unshift({});
515         return Object.merge.apply(null, args);
518 this.$lambda = Function.from;
519 this.$mixin = Object.merge;
520 this.$random = Number.random;
521 this.$splat = Array.from;
522 this.$time = Date.now;
524 this.$type = function(object){
525         var type = typeOf(object);
526         if (type == 'elements') return 'array';
527         return (type == 'null') ? false : type;
530 this.$unlink = function(object){
531         switch (typeOf(object)){
532                 case 'object': return Object.clone(object);
533                 case 'array': return Array.clone(object);
534                 case 'hash': return new Hash(object);
535                 default: return object;
536         }
539 //</1.2compat>
541 })();