"Square" Factor Generator

Generates a list of factors for a given number, then determines the most "square" factors for the sprite generator. This way, there's the least amount of whitespace in an image made of tiles.

by phyreman

JavaScript

Number.prototype.even = function () {
    "use strict";
    return 0 === Number(this) % 2;
};
Number.prototype.odd = function () {
    "use strict";
    return 1 === Number(this) % 2;
};
Number.prototype.factors = function () {
    "use strict";
    var a,
        b = 0,
        c = [];
    while (b++ <= this) {
        a = this / b;
        if (a === Math.floor(a)) {
            c.push(b);
        }
    }
    return c;
};

var rootFactor = function (input) {
    "use strict";
    var factors = input.factors(),
        root = Math.floor((factors.length - 1) / 2),
        i = 0,
        output,
        diff,
        best,
        bestDiff;

    if (factors.length.odd()) {
        output = [factors[root], factors[root]];
    } else if (arguments[1] && input - arguments[1] > 5) {
        output = [factors[root], factors[root + 1]];
    } else {
        best = [factors[root], factors[root + 1]];

        while (i++ < 5) {
            factors = (input + i).factors();
            root = Math.floor((factors.length - 1) / 2);
            diff = factors[root + 1] - factors[root];

            if (factors.length.odd()) {
                best = [factors[root], factors[root]];
            }
            bestDiff = best[1] - best[0];
            if (diff < bestDiff && (best[0] * best[1] > factors[root + 1] - factors[root])) {
                best = [factors[root], factors[root + 1]];
            }
        }
        output = best;
    }
    return output;
};