Never been to DZone Snippets before?

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

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Convert single object to List

Works with varargs in Java 1.6

List<String> list = java.util.Arrays.asList("foo");

JavaScript versions of the functions described in Martin Fowler's article "CollectionClosureMethod"

See the original article at http://www.martinfowler.com/bliki/CollectionClosureMethod.html.

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;
};
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS