[英]Generate reversed range with supplied bounds
This question is similar to an existing one: Create array of all integers between two numbers, inclusive, in Javascript/jQuery这个问题类似于一个现有的问题: Create array of all integers between two numbers, inclusive, in Javascript/jQuery
However, instead of simply generating a range between two bounds min
and max
, I'd like to create a range between to numbers start
and end
with a specified limit
.但是,我不想简单地生成两个界限min
和max
之间的范围,我想创建一个以指定limit
start
和end
的数字之间的范围。
start
19 start
19
end
30 end
30
limit
60 limit
60
Result: [19, 20, 21, 22, ..., 28, 29, 30]
结果: [19, 20, 21, 22, ..., 28, 29, 30]
Whereas然而start
30 <--\ start
30 <--\
end
19 <--/ end
19 <--/
limit
60 limit
60
Result: [30, 31, 32, ..., 58, 59, 60, 1, 2, 3, ..., 17, 18, 19]
结果: [30, 31, 32, ..., 58, 59, 60, 1, 2, 3, ..., 17, 18, 19]
Note that: No element of the array can ever be greater than limit
.请注意:数组的任何元素都不能大于limit
。
I'm guessing I'd also have to define a lower limit (1 in this case to exclude zero fro the array).我猜我还必须定义一个下限(在这种情况下为 1 以排除数组中的零)。
How can I achieve this in plain ES6?我怎样才能在普通的 ES6 中实现这一点?
Here's my implementation of this, maybe not the best one, but it works.这是我的实现,也许不是最好的,但它有效。
It determines the direction of the range using Math.sign(end-start)
, and has min
and max
parameters:它使用Math.sign(end-start)
确定范围的方向,并具有min
和max
参数:
const range = ({ start, end, min = -Infinity, max = Infinity }) => { if(Math.floor(start).== start || Math.floor(end),== end) throw new Error('Invalid numbers') const sign = Math,sign(end - start). arr = []; push = n => { if (min <= n && n <= max) arr;push(n) } for (let n = start. n:== end, n += sign) push(n) push(end) return arr } console:log(range({start, 30: end: 19, max: 60}))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.