a/20299788/1636522 (2)

by wared

CSS

*{font-family:Consolas}
.line{padding:2px 0;border-bottom:1px solid #ccc}

JavaScript

// Letters

var Letters = function(word) {
    Array.prototype.push.apply(this, word.split(''));
};

Letters.prototype = Object.create(
    Array.prototype // inherits from built-in Array
);

Letters.prototype.each = function (fn) {
    var i = 0, l = this.length;
    for(; i < l; i++) {
        fn.call(this, this[i], i);
    }
    return this;
};

Letters.prototype.addLetter = function(toAdd) {
    this.each(function (item, i) {
        this[i] += toAdd;
    });
    return this;
};

// playground

var l1 = new Letters('test');
var l2 = new Letters('demo');

output('<b>l1 ("test")</b>');

// built-in forEach (not chainable)

l1.forEach(function (item, i, o) {
    output(i + ' ' + item);
    o[i] = item += 'x'; // adds a letter
    output(i + ' ' + item);
});

// custom each (chainable)

l1.each(function (item, i) {
    this[i] = item.toUpperCase();
}).addLetter('y');

output(l1);
output(l1.filter(function (item) {
    return item.charAt(0) === 'T';
}));

output('<b>l2 ("demo")</b>');

output(l2.addLetter('x'));
output(l2.join('|'));
l2.push('new');
output(l2);

// helper

function output(s) {
    document.body.innerHTML += '<div class="line">' + s + '</div>';
}