Does JavaScript have a method like “range()” to generate a range within the supplied bounds?

后端 未结 30 2765
广开言路
广开言路 2020-11-22 00:51

In PHP, you can do...

range(1, 3); // Array(1, 2, 3)
range(\"A\", \"C\"); // Array(\"A\", \"B\", \"C\")

That is, there is a function that l

30条回答
  •  盖世英雄少女心
    2020-11-22 01:36

    Using Harmony generators, supported by all browsers except IE11:

    var take = function (amount, generator) {
        var a = [];
    
        try {
            while (amount) {
                a.push(generator.next());
                amount -= 1;
            }
        } catch (e) {}
    
        return a;
    };
    
    var takeAll = function (gen) {
        var a = [],
            x;
    
        try {
            do {
                x = a.push(gen.next());
            } while (x);
        } catch (e) {}
    
        return a;
    };
    
    var range = (function (d) {
        var unlimited = (typeof d.to === "undefined");
    
        if (typeof d.from === "undefined") {
            d.from = 0;
        }
    
        if (typeof d.step === "undefined") {
            if (unlimited) {
                d.step = 1;
            }
        } else {
            if (typeof d.from !== "string") {
                if (d.from < d.to) {
                    d.step = 1;
                } else {
                    d.step = -1;
                }
            } else {
                if (d.from.charCodeAt(0) < d.to.charCodeAt(0)) {
                    d.step = 1;
                } else {
                    d.step = -1;
                }
            }
        }
    
        if (typeof d.from === "string") {
            for (let i = d.from.charCodeAt(0); (d.step > 0) ? (unlimited ? true : i <= d.to.charCodeAt(0)) : (i >= d.to.charCodeAt(0)); i += d.step) {
                yield String.fromCharCode(i);
            }
        } else {
            for (let i = d.from; (d.step > 0) ? (unlimited ? true : i <= d.to) : (i >= d.to); i += d.step) {
                yield i;
            }
        }
    });
    

    Examples

    take

    Example 1.

    take only takes as much as it can get

    take(10, range( {from: 100, step: 5, to: 120} ) )

    returns

    [100, 105, 110, 115, 120]

    Example 2.

    to not neccesary

    take(10, range( {from: 100, step: 5} ) )

    returns

    [100, 105, 110, 115, 120, 125, 130, 135, 140, 145]

    takeAll

    Example 3.

    from not neccesary

    takeAll( range( {to: 5} ) )

    returns

    [0, 1, 2, 3, 4, 5]

    Example 4.

    takeAll( range( {to: 500, step: 100} ) )

    returns

    [0, 100, 200, 300, 400, 500]

    Example 5.

    takeAll( range( {from: 'z', to: 'a'} ) )

    returns

    ["z", "y", "x", "w", "v", "u", "t", "s", "r", "q", "p", "o", "n", "m", "l", "k", "j", "i", "h", "g", "f", "e", "d", "c", "b", "a"]

提交回复
热议问题