Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
TypeScript Create a countdown iterator that counts from a to b

I have a task to create a countdown iterator that counts from a to b. For example:

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};  

And i have the next test units:

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});
    });
});  

I created the iterator this way :

function countdown(a:number, b:number) {
    let arr = [];
    while(a>=b){
        arr.push(a--)
    }

    // const next = () =>{

    // }
    
    return arr
}  

It passes the unit tests,but the problem is,how to create .next() like in the example and show that object with the start value and done ? Thanks in advance! I'm new in TypeScript and i dont know how to do this

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You are looking for a generator function:

function* countdown(a:number, b:number) {
    while(a>=b){
        yield a--;
    }
}

console.log([...countdown(10, 1)]);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!