rozdział: Metody
==================
var a = ['a', 'b', 'c'];
var b = ['x', 'y', 'z'];
var c = a.concat(b, true);
// c wynosi ['a', 'b', 'c', 'x', 'y', 'z', true]
    
    
====================================
var a = ['a', 'b', 'c'];
a.push('d');
var c = a.join('');  // c wynosi 'abcd'
    
    
====================================
var a = ['a', 'b', 'c'];
var c = a.pop()  // a wynosi ['a', 'b']; c wynosi 'c'
   
    
====================================
Array.method('pop', function (  ) {
    return this.splice(this.length - 1, 1)[0];
});
    
    
====================================
var a = ['a', 'b', 'c'];
var b = ['x', 'y', 'z'];
var c = a.push(b, true);
// a wynosi ['a', 'b', 'c', ['x', 'y', 'z'], true]; c wynosi 5
    
    
====================================
Array.method('push', function () {
   this.splice.apply(
      this,
      [this.length, 0].concat(Array.prototype.slice.apply(arguments)));
   return this.length;
});
 
    
====================================
var a = ['a', 'b', 'c'];
var b = a.reverse();
// a i b wynoszą ['c', 'b', 'a'] 
    
    
====================================
var a = ['a', 'b', 'c'];
var c = a.shift();  // a wynosi ['b', 'c']; c wynosi 'a'
    
    
====================================
Array.method('shift', function (  ) {
    return this.splice(0, 1)[0];
});
    
    
====================================
var a = ['a', 'b', 'c'];
var b = a.slice(0, 1);  // b wynosi ['a']
var c = a.slice(1);     // c wynosi ['b', 'c']
var d = a.slice(1,2);   // d wynosi ['b']
    
    
====================================
var n = [4, 8, 15, 16, 23, 42];
n.sort(  );
// n wynosi [15, 16, 23, 4, 42, 8]
    
    
====================================
n.sort(function (a, b) {
    return a − b;
});
// n wynosi [4, 8, 15, 16, 23, 42];
    
    
====================================
var m = ['aa', 'bb', 'a', 4, 8, 15, 16, 23, 42];
m.sort(function (a, b) {
    if (a === b) {
        return 0;
    }
    if (typeof a === typeof b) {
        return a < b ? −1 : 1;
    }
    return typeof a < typeof b ? −1 : 1;
});
// m wynosi [4, 8, 15, 16, 23, 42, 'a', 'aa', 'bb']
    
    
====================================
// Funkcja pobiera nazwę właściwości i zwraca 
// funkcję porównującą, która może być użyta do posortowania 
// dowolnej tablicy obiektów zawierających właściwość o tej nazwie.

var by = function (name) {
   return function (o, p) {
      var a, b;
      if (typeof o === 'object' && typeof p === 'object' && o && p) {
         a = o[name];
         b = p[name];
         if (a === b) {
            return 0;
         }
         if (typeof a === typeof b) {
            return a < b ? -1 : 1;
         }
         return typeof a < typeof b ? -1 : 1;
      } else {
         throw {
            name: 'Error',
            message: 'Oczekiwano obiektu podczas sortowania po ' + name
         };
      }
   };
};

var s = [
   {first: 'Joe',   last: 'Besser'},
   {first: 'Moe',   last: 'Howard'},
   {first: 'Joe',   last: 'DeRita'},
   {first: 'Shemp', last: 'Howard'},
   {first: 'Larry', last: 'Fine'},
   {first: 'Curly', last: 'Howard'}
];
s.sort(by('first'));
// s wynosi [
//  {first: 'Curly', last: 'Howard'},
//  {first: 'Joe',   last: 'Besser'},
//  {first: 'Joe',   last: 'DeRita'},
//  {first: 'Larry', last: 'Fine'},
/   {first: 'Moe',   last: 'Howard'},
//  {first: 'Shemp', last: 'Howard'}
// ]
    
    
====================================
s.sort(by('first')).sort(by('last'));
    
    
====================================
// Funkcja pobiera nazwę właściwości i opcjonalną
// dodatkową funkcję porównującą i zwraca 
// funkcję porównującą, która może być użyta do posortowania 
// dowolnej tablicy obiektów zawierających właściwość o tej nazwie.
// Dodatkowa funkcja porównująca jest używana do porównań, gdy
// o[name] i p[name] są równe.

var by = function (name, minor) {
   return function (o, p) {
      var a, b;
      if (o && p && typeof o === 'object' && typeof p === 'object') {
         a = o[name];
         b = p[name];
         if (a === b) {
            return typeof minor === 'function' ? minor(o, p) : 0;
         }
         if (typeof a === typeof b) {
            return a < b ? -1 : 1;
         }
         return typeof a < typeof b ? -1 : 1;
      } else {
         throw {
            name: 'Error',
            message: 'Oczekiwano obiektu podczas sortowania po ' + name
         };
      }
   };
};

s.sort(by('last', by('first')));  
// s wynosi [
//  {first: 'Joe', last: 'Besser'},
//  {first: 'Joe', last: 'DeRita'},
//  {first: 'Larry', last: 'Fine'},
//  {first: 'Curly', last: 'Howard'},
//  {first: 'Moe', last: 'Howard'},
//  {first: 'Shemp', last: 'Howard'}
// ]
    
    
====================================
var a = ['a', 'b', 'c'];
var r = a.splice(1, 1, 'ache', 'bug');
// a wynosi ['a', 'ache', 'bug', 'c']
// r wynosi ['b']
    
    
====================================
Array.method('splice', function (start, deleteCount) {
    var max = Math.max,
        min = Math.min,
        delta,
        element,
        insertCount = max(arguments.length - 2, 0),
        k = 0,
        len = this.length,
        new_len,
        result = [],
        shift_count;

    start = start || 0;
    if (start < 0) {
        start += len;
    }
    start = max(min(start, len), 0);
    deleteCount = max(min(typeof deleteCount === 'number' ?
            deleteCount : len, len − start), 0);
    delta = insertCount − deleteCount;
    new_len = len + delta;
    while (k < deleteCount) {
        element = this[start + k];
        if (element !== undefined) {
            result[k] = element;
        }
        k += 1;
    }
    shift_count = len - start - deleteCount;
    if (delta < 0) {
        k = start + insertCount;
        while (shift_count) {
            this[k] = this[k − delta];
            k += 1;
            shift_count −= 1;
        }
        this.length = new_len;
    } else if (delta > 0) {
        k = 1;
        while (shift_count) {
            this[new_len − k] = this[len − k];
            k += 1;
            shift_count −= 1;
        }
    }
    for (k = 0; k < insertCount; k += 1) {
        this[start + k] = arguments[k + 2];
    }
    return result;
});
    
    
====================================
var a = ['a', 'b', 'c'];
var r = a.unshift('?', '@');
// a wynosi ['?', '@', 'a', 'b', 'c']
// r wynosi 5
    
    
====================================
Array.method('unshift', function (  ) {
    this.splice.apply(this,
        [0, 0].concat(Array.prototype.slice.apply(arguments)));
    return this.length;
});
    
    
====================================
Function.method('bind', function (that) {

   // Zwracamy funkcję, która będzie wywoływała tą funkcję
   // jak gdyby była to metoda obiektu that

   var method = this,
       slice = Array.prototype.slice,
       args = slice.apply(arguments, [1]);
   return function () {
      return method.apply(that, args.concat(slice.apply(arguments, [0])));
   };
});

var x = function () {
   return this.value;
}.bind({value: 666});
alert(x()); // 666
    
    
====================================
document.writeln(Math.PI.toExponential(0));
document.writeln(Math.PI.toExponential(2));
document.writeln(Math.PI.toExponential(7));
document.writeln(Math.PI.toExponential(16));
document.writeln(Math.PI.toExponential(  ));

// Produces

3e+0
3.14e+0
3.1415927e+0
3.1415926535897930e+0
3.141592653589793e+0
    
    
====================================
document.writeln(Math.PI.toFixed(0));
document.writeln(Math.PI.toFixed(2));
document.writeln(Math.PI.toFixed(7));
document.writeln(Math.PI.toFixed(16));
document.writeln(Math.PI.toFixed(  ));

// Wynik:

3
3.14
3.1415927
3.1415926535897930
3
    
    
====================================
document.writeln(Math.PI.toPrecision(2));
document.writeln(Math.PI.toPrecision(7));
document.writeln(Math.PI.toPrecision(16));
document.writeln(Math.PI.toPrecision(  ));

// Wynik:

3.1
3.141593
3.141592653589793
3.141592653589793
    
    
====================================
document.writeln(Math.PI.toString(2));
document.writeln(Math.PI.toString(8));
document.writeln(Math.PI.toString(16));
document.writeln(Math.PI.toString(  ));

// Wynik:

11.001001000011111101101010100010001000010110100011
3.1103755242102643
3.243f6a8885a3
3.141592653589793
    
    
====================================
var a = {member: true};
var b = Object.beget(a);             // z rozdziału 3
var t = a.hasOwnProperty('member');  // t wynosi true
var u = b.hasOwnProperty('member');  // u wynosi false
var v = b.member                     // v wynosi true
    
    
====================================
// Rozbijamy prosty dokument html na znaczniki i teksty.
// (Definicja metody entityify znajduje się w opisie metody string.replace)

// Dla każdego znacznika lub tekstu tworzymy tablicę zawierającą:
// [0] cały dopasowany znacznik lub tekst
// [1] nazwę znacznika
// [2] znak ukośnika /, jeśli jest
// [3] atrybuty, jeśli są

var text = '<html><body bgcolor=linen><p>' + 
           'This is <b>bold<\/b>!<\/p><\/body><\/html>';
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;

while ((a = tags.exec(text))) {
   for (i = 0; i < a.length; i += 1) {
      document.writeln(('[' + i + '] ' + a[i]).entityify());
   }
   document.writeln();
}

// Wynik:

[0] <html>
[1]
[2] html
[3]

[0] <body bgcolor=linen>
[1]
[2] body
[3]  bgcolor=linen

[0] <p>
[1]
[2] p
[3]

[0] This is
[1] undefined
[2] undefined
[3] undefined

[0] <b>
[1]
[2] b
[3]

[0] bold
[1] undefined
[2] undefined
[3] undefined

[0] </b>
[1] /
[2] b
[3]

[0] !
[1] undefined
[2] undefined
[3] undefined

[0] </p>
[1] /
[2] p
[3]

[0] </body>
[1] /
[2] body
[3]

[0] </html>
[1] /
[2] html
[3]
    
    
====================================
var b = /&.+;/.test('frank &amp; beans');
// b ma wartość true
    
    
====================================
RegExp.method('test', function (string) {
    return this.exec(string) !== null;
});
    
    
====================================
var name = 'Curly';
var initial = name.charAt(0);    //'C'
    
    
====================================
String.method('charAt', function (  ) {
    return this.slice(0, 1);
});
    
    
====================================
var name = 'Curly';
var initial = name.charCodeAt(0);    //67
    
    
====================================
var s = 'C'.concat('a', 't');    //'Cat'
    
    
====================================
var text = 'Mississippi';
var p = text.indexOf('ss');    // 2
p = text.indexOf('ss', 3);     // 5
p = text.indexOf('ss', 6);     // −1
    
    
====================================
var text = 'Mississippi';
var p = text.lastIndexOf('ss');    // 5
p = text.lastIndexOf('ss', 3);     // 2
p = text.lastIndexOf('ss', 6);     // 5
    
    
====================================
var m = ['AAA', 'A', 'aa', 'a', 'Aa', 'aaa'];
m.sort(function (a, b) {
    return a.localeCompare(b);
});
// m (przy pewnych ustawieniach regionalnych) wynosi
// ['a', 'A', 'aa', 'Aa', 'aaa', 'AAA']
   
    
====================================
var text = '<html><body bgcolor=linen><p>' +
        'This is <b>bold<\/b>!<\/p><\/body><\/html>';
var tags = /[^<>]+|<(\/?)([A-Za-z]+)([^<>]*)>/g;
var a, i;

a = text.match(tags);
for (i = 0; i < a.length; i += 1) {
    document.writeln(('[' + i + '] ' + a[i]).entityify(  ));
}

// Wynik:

[0] <html>
[1] <body bgcolor=linen>
[2] <p>
[3] This is
[4] <b>
[5] bold
[6] </b>
[7] !
[8] </p>
[9] </body>
[10] </html>
    
    
====================================
var result = "mother_in_law".replace('_', '-');
    
    
====================================
// Pobieramy 3 cyfry w nawiasach

var oldareacode = /\((\d{3})\)/g;
var p = '(555)666-1212'.replace(oldareacode, '$1-');
// p wynosi '555-666-1212'
    
    
====================================
String.method('entityify', function () {
   
   var character = {
      '<' : '&lt;',
      '>' : '&gt;',
      '&' : '&amp;',
      '"' : '&quot;'
   };

   // Zwracamy metodę string.entityify, która z kolei
   // zwraca wynik wywołania metody replace, której 
   // funkcja replaceValue zwraca zamiennik pobrany z obiektu.
   // Użycie obiektu z reguły jest szybsze od instrukcji switch.

   return function () {
      return this.replace(/[<>&"]/g, function (c) {
         return character[c];
      });
   };
}());
alert("<&>".entityify());  // &lt;&amp;&gt;
    
    
====================================
var text = 'and in it he says "Any damn fool could';
var pos = text.search(/["']/);    //18
    
    
====================================
var text = 'and in it he says "Any damn fool could';
var a = text.slice(18);
// a wynosi '"Any damn fool could'
var b = text.slice(0, 3);
// b wynosi 'and'
var c = text.slice(-5);
// c wynosi 'could'
var d = text.slice(19, 32);
// d wynosi 'Any damn fool'
    
    
====================================
var digits = '0123456789';
var a = digits.split('', 5);
// a wynosi ['0', '1', '2', '3', '4']
    
    
====================================
var ip = '192.168.1.0';
var b = ip.split('.');
// b wynosi ['192', '168', '1', '0']

var c = '|a|b|c|'.split('|');
// c wynosi ['', 'a', 'b', 'c', '']

var text = 'last,  first ,middle';
var d = text.split(/\s*,\s*/);
// d wynosi [
//    'last',
//    'first',
//    'middle'
// ]
    
    
====================================
var e = text.split(/\s*(,)\s*/);
// e wynosi [
//    'last',
//    ',',
//    'first',
//    ',',
//    'middle'
// ]
    
    
====================================
var f = '|a|b|c|'.split(/\|/);
// f wynosi ['a', 'b', 'c'] lub
// ['', 'a', 'b', 'c', ''] w zależności od systemu
    
    
====================================
var a = String.fromCharCode(67, 97, 116);
// a wynosi 'Cat'
    
    
==================