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

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

    ... more range, using a generator function.

    function range(s, e, str){
      // create generator that handles numbers & strings.
      function *gen(s, e, str){
        while(s <= e){
          yield (!str) ? s : str[s]
          s++
        }
      }
      if (typeof s === 'string' && !str)
        str = 'abcdefghijklmnopqrstuvwxyz'
      const from = (!str) ? s : str.indexOf(s)
      const to = (!str) ? e : str.indexOf(e)
      // use the generator and return.
      return [...gen(from, to, str)]
    }
    
    // usage ...
    console.log(range('l', 'w'))
    //=> [ 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w' ]
    
    console.log(range(7, 12))
    //=> [ 7, 8, 9, 10, 11, 12 ]
    
    // first 'o' to first 't' of passed in string.
    console.log(range('o', 't', "ssshhhooooouuut!!!!"))
    // => [ 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 't' ]
    
    // only lowercase args allowed here, but ...
    console.log(range('m', 'v').map(v=>v.toUpperCase()))
    //=> [ 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V' ]
    
    // => and decreasing range ...
    console.log(range('m', 'v').map(v=>v.toUpperCase()).reverse())
    
    // => ... and with a step
    console.log(range('m', 'v')
              .map(v=>v.toUpperCase())
              .reverse()
              .reduce((acc, c, i) => (i % 2) ? acc.concat(c) : acc, []))
    
    // ... etc, etc.
    

    Hope this is useful.

提交回复
热议问题