DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

JavaScript Versions Of The Functions Described In Martin Fowler's Article "CollectionClosureMethod"

08.11.2005
| 2787 views |
  • submit to reddit
        See the original article at <a href="http://www.martinfowler.com/bliki/CollectionClosureMethod.html">http://www.martinfowler.com/bliki/CollectionClosureMethod.html</a>.

These implement all the methods except the sorting related ones.
Array.prototype.select = function(detect) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            result.push(this[i]);
        }
    }
    return result;
};

Array.prototype.reject = function(detect) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        if (!detect(this[i])) {
            result.push(this[i]);
        }
    }
    return result;
};

Array.prototype.partition = function(detect) {
    var yeses = [];
    var nos   = [];
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            yeses.push(this[i]);
        } else {
            nos.push(this[i]);
        }
    }
    return [yeses, nos];
};

Array.prototype.all = function(detect) {
    for (var i = 0; i < this.length; ++i) {
        if (!detect(this[i])) {
            return false;
        }
    }
    return true;
};

Array.prototype.any = function(detect) {
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            return true;
        }
    }
    return false;
};

Array.prototype.find = function(detect, ifNone) {
    for (var i = 0; i < this.length; ++i) {
        if (detect(this[i])) {
            return this[i];
        }
    }

    if (ifNone === null) {
        return null;
    }

    return ifNone();
};

Array.prototype.map = function(mapper) {
    var result = [];
    for (var i = 0; i < this.length; ++i) {
        result.push(mapper(this[i]));
    }
    return result;
};

Array.prototype.inject = function(initial, reducer) {
    var result = initial;
    for (var i = 0; i < this.length; ++i) {
        result = reducer(result, this[i]);
    }
    return result;
};