TypeScript 创建一个从 a 数到 b 的倒计时迭代器
TypeScript Create a countdown iterator that counts from a to b
我的任务是创建一个从 a 计数到 b 的倒计时迭代器。
例如:
console.log([...countdown(10, 1)]); // [10,9,8,7,6,5,4,3,2,1]
const counter = countdown(5,2);
console.log(counter.next()); // {value: 5, done: false};
我还有下一个测试单元:
describe('countdown', () => {
it('should return [10,9,8,7,6,5,4,3,2,1] for given input (10, 1)', () => {
assert.deepStrictEqual([...countdown(10, 1)], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
});
it('should return [5,4,3,2,1,0] for given input (5, 0)', () => {
assert.deepStrictEqual([...countdown(5, 0)], [5, 4, 3, 2, 1, 0]);
});
it('should return [15,14,13,12,11,10] for given input (15, 10)', () => {
assert.deepStrictEqual([...countdown(15, 10)], [15, 14, 13, 12, 11, 10]);
});
it('should return {value: 3, done: false} for given input (3, 0)', () => {
assert.deepStrictEqual(countdown(3, 0).next(), {value: 3, done: false});
});
});
我是这样创建迭代器的:
function countdown(a:number, b:number) {
let arr = [];
while(a>=b){
arr.push(a--)
}
// const next = () =>{
// }
return arr
}
它通过了单元测试,但问题是,如何像示例中那样创建 .next() 并显示具有起始值和完成的对象?提前致谢!我是 TypeScript 的新手,我不知道该怎么做
您正在寻找 generator function:
function* countdown(a:number, b:number) {
while(a>=b){
yield a--;
}
}
console.log([...countdown(10, 1)]);
我的任务是创建一个从 a 计数到 b 的倒计时迭代器。 例如:
console.log([...countdown(10, 1)]); // [10,9,8,7,6,5,4,3,2,1]
const counter = countdown(5,2);
console.log(counter.next()); // {value: 5, done: false};
我还有下一个测试单元:
describe('countdown', () => {
it('should return [10,9,8,7,6,5,4,3,2,1] for given input (10, 1)', () => {
assert.deepStrictEqual([...countdown(10, 1)], [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]);
});
it('should return [5,4,3,2,1,0] for given input (5, 0)', () => {
assert.deepStrictEqual([...countdown(5, 0)], [5, 4, 3, 2, 1, 0]);
});
it('should return [15,14,13,12,11,10] for given input (15, 10)', () => {
assert.deepStrictEqual([...countdown(15, 10)], [15, 14, 13, 12, 11, 10]);
});
it('should return {value: 3, done: false} for given input (3, 0)', () => {
assert.deepStrictEqual(countdown(3, 0).next(), {value: 3, done: false});
});
});
我是这样创建迭代器的:
function countdown(a:number, b:number) {
let arr = [];
while(a>=b){
arr.push(a--)
}
// const next = () =>{
// }
return arr
}
它通过了单元测试,但问题是,如何像示例中那样创建 .next() 并显示具有起始值和完成的对象?提前致谢!我是 TypeScript 的新手,我不知道该怎么做
您正在寻找 generator function:
function* countdown(a:number, b:number) {
while(a>=b){
yield a--;
}
}
console.log([...countdown(10, 1)]);