'formater' -> 'formatter'
[euphorik.git] / js / betterjs.js
1 // coding: utf-8
2 // some improvements for JavaScript
3
4 /**
5 * For each object properties execute f(p, v) where p is the propertie name and v its value.
6 * Does not traverse the protypes properties.
7 * FIXME : Should be "Object.prototype.each = function(f)" but doen't supported by jQuery.
8 * @o The object.
9 * @f The function f(p, v).
10 */
11 //Object.prototype.each = function(f) {
12 var objectEach = function(o, f) {
13 for (var k in o) {
14 if (o.hasOwnProperty(k)) {
15 f(k, o[k]);
16 }
17 }
18 };
19
20 /**
21 * Return the number of properties of a given object.
22 * Does not count the prototypes properties.
23 * @o The object.
24 */
25 var objectMemberCount = function(o) {
26 var nb = 0;
27 for (var k in o) {
28 if (o.hasOwnProperty(k)) {
29 nb += 1;
30 }
31 }
32 return nb;
33 };
34
35 /**
36 * Call a function to all value of the Array.
37 * @f The function f(i, v) where i is the index and v the value.
38 */
39 Array.prototype.each = function(f) {
40 for (var i = 0; i < this.length; i++) {
41 f(i, this[i]);
42 }
43 };
44
45 /**
46 * Map a function to all value of the Array.
47 * @f The function f(v) -> v' where v is the old value and v' the new one.
48 */
49 Array.prototype.map = function(f) {
50 for (var i = 0; i < this.length; i++) {
51 this[i] = f(this[i]);
52 }
53 };
54
55 /**
56 * Remove all space character (space, tab) at the begining and the end of the String.
57 */
58 String.prototype.trim = function() {
59 return jQuery.trim(this); // anciennement : this.replace(/^\s+|\s+$/g, "");
60 };
61
62 /**
63 * Remove all space character (space, tab) at the begining of the String.
64 */
65 String.prototype.ltrim = function() {
66 return this.replace(/^\s+/, "");
67 };
68
69 /**
70 * Remove all space character (space, tab) at the end of the String.
71 */
72 String.prototype.rtrim = function() {
73 return this.replace(/\s+$/, "");
74 };
75
76 /**
77 * (Not use for the moment)
78 * See : http://www.coolpage.com/developer/javascript/Correct%20OOP%20for%20Javascript.html
79 *
80 * Example :
81 *
82 * function Mammal(name) {
83 * this.name = name;
84 * }
85 *
86 * Cat.Inherits(Mammal);
87 * function Cat(name) {
88 * this.Super(Mammal, name);
89 * }
90 */
91 /*Object.prototype.Super = function(parent) {
92 if(arguments.length > 1) {
93 parent.apply( this, Array.prototype.slice.call( arguments, 1 ) );
94 } else {
95 parent.call( this );
96 }
97 }
98 Function.prototype.Inherits = function(parent) {
99 this.prototype = new parent();
100 this.prototype.constructor = this;
101 }*/