在PHP中,您可以。。。
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。
JavaScript本机是否有内置的功能?如果没有,我将如何实施?
在PHP中,您可以。。。
range(1, 3); // Array(1, 2, 3)
range("A", "C"); // Array("A", "B", "C")
也就是说,有一个函数可以通过传递上下限来获得一系列数字或字符。
JavaScript本机是否有内置的功能?如果没有,我将如何实施?
当前回答
一个可以在任一方向工作的衬垫:
const range = (a,b)=>Array(Math.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));
请参阅实际操作:
常量范围=(a,b)=>数组(数学.abs(a-b)+1).fill(a).map((v,i)=>v+i*(a>b?-1:1));console.log(范围(1,4));console.log(范围(4,1));
其他回答
Python风格的方式:
range = (start, end, step) => {
let arr = []
for(let n=start;n<end;n+=(step||1)) arr.push(n)
return arr;
}
在边界内生成整数数组的递归解决方案。
function intSequence(start, end, n = start, arr = []) {
return (n === end) ? arr.concat(n)
: intSequence(start, end, start < end ? n + 1 : n - 1, arr.concat(n));
}
$> intSequence(1, 1)
<- Array [ 1 ]
$> intSequence(1, 3)
<- Array(3) [ 1, 2, 3 ]
$> intSequence(3, -3)
<- Array(7) [ 3, 2, 1, 0, -1, -2, -3 ]
要紧密复制的类型脚本函数
/**
* Create a generator from 0 to stop, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} stop
* @returns {Iterable<number>}
*/
export function range(stop: number | BigNumber): Iterable<number>
/**
* Create a generator from start to stop, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} start
* @param {number | BigNumber} stop
* @returns {Iterable<number>}
*/
export function range(
start: number | BigNumber,
stop: number | BigNumber,
): Iterable<number>
/**
* Create a generator from start to stop while skipping every step, useful for iteration. Similar to range in Python.
* See: https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp
* See: https://docs.python.org/3/library/stdtypes.html#ranges
* @param {number | BigNumber} start
* @param {number | BigNumber} stop
* @param {number | BigNumber} step
* @returns {Iterable<number>}
*/
export function range(
start: number | BigNumber,
stop: number | BigNumber,
step: number | BigNumber,
): Iterable<number>
export function* range(a: unknown, b?: unknown, c?: unknown): Iterable<number> {
const getNumber = (val: unknown): number =>
typeof val === 'number' ? val : (val as BigNumber).toNumber()
const getStart = () => (b === undefined ? 0 : getNumber(a))
const getStop = () => (b === undefined ? getNumber(a) : getNumber(b))
const getStep = () => (c === undefined ? 1 : getNumber(c))
for (let i = getStart(); i < getStop(); i += getStep()) {
yield i
}
}
我的实施
export function stringRange(a: string, b: string) {
let arr = [a + ''];
const startPrefix = a.match(/([\D])+/g);
const endPrefix = b.match(/([\D])+/g);
if ((startPrefix || endPrefix) && (Array.isArray(startPrefix) && startPrefix[0]) !== (Array.isArray(endPrefix) && endPrefix[0])) {
throw new Error('Series number does not match');
}
const startNum = a.match(/([\d])+/g);
const endNum = b.match(/([\d])+/g);
if (!startNum || !endNum) {
throw new Error('Range is not valid');
}
let start = parseInt(startNum[0], 10);
let end = parseInt(endNum[0], 10);
if (start > end) {
throw new Error('Ending value should be lessesr that starting value');
}
while (start !== end) {
start++;
arr.push(startPrefix ? startPrefix[0] + (start + '').padStart(startNum[0].length, '0') : start + '');
}
return arr;
}
样本结果
// console.log(range('0', '10'));
// console.log(range('10', '10'));
// console.log(range('10', '20'));
// console.log(range('10', '20000'));
// console.log(range('ABC10', 'ABC23'));
// console.log(range('ABC10', 'ABC2300'));
// console.log(range('ABC10', 'ABC09')); --> Failure case
// console.log(range('10', 'ABC23')); --> Failure case
// console.log(range('ABC10', '23')); --> Failure case
已经给出了非常好的答案,但我没有看到ES6迭代器的完整使用来实现范围的完整实现,所以这里是:
/**
* inspired by Python's built-in range utility function
* implemented using ES6 Iterable, Iterator protolols (interfaces)
*/
class Range {
constructor(...args) {
this.start = args.length <= 1 ? 0 : args[0];
this.end = args.length <= 1 ? args[0] || 0 : args[1];
this.step = args.length <= 2 ? 1 : args[2];
}
[Symbol.iterator]() {
return this;
}
next() {
if (this.end > this.start) {
const result = { done: false, value: this.start };
this.start = this.start + this.step;
return result;
} else return { done: true, value: undefined };
}
}
/**
* Symbol.iterator is part of the couple of inbuilt symbols
* available in JavaScript. It allows for hooking into the
* inbuilt for of iteration mechanism. This is why the
* Symbol.iterator comes into play when talking about
* iterables and iterators in JavaScript.
*/
function range(...args) {
return new Range(...args);
}
console.log([...range(4)]); // [0, 1, 2, 3]
console.log([...range(2, 5)]); // [2, 3, 4]
console.log([...range(1, 10, 3)]); // [1, 4, 7]