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

后端 未结 30 3483
广开言路
广开言路 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:48

    An interesting challenge would be to write the shortest function to do this. Recursion to the rescue!

    function r(a,b){return a>b?[]:[a].concat(r(++a,b))}
    

    Tends to be slow on large ranges, but luckily quantum computers are just around the corner.

    An added bonus is that it's obfuscatory. Because we all know how important it is to hide our code from prying eyes.

    To truly and utterly obfuscate the function, do this:

    function r(a,b){return (ab?[]:[a]).sort(function(a,b){return a-b})}
    

提交回复
热议问题