Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add generator method #7

Closed
zakaria-chahboun opened this issue Sep 23, 2020 · 2 comments · Fixed by #24
Closed

Add generator method #7

zakaria-chahboun opened this issue Sep 23, 2020 · 2 comments · Fixed by #24

Comments

@zakaria-chahboun
Copy link

How we can using it in for loop?

@sindresorhus
Copy link
Owner

I assume you're asking how to use it as an iterable (it being a generator), because just using it normally in a for loop is pretty easy already.

I guess we could potentially add a .generator() method so you could do something like:

const iterator = uniqueRandom.generator({
  minimum: 0,
  maximum: 10,
  count: 3
});

for (const number of iterator) {
  console.log(number);
  //=> 3
  //=> 7
  //=> 2
}

Alternatively, the minimum/maximum could be replaced by a range: [0, 10] option. Depending on whether we want each part to be optional.

@sindresorhus sindresorhus changed the title in loop! Add generator method Sep 23, 2020
@zakaria-chahboun
Copy link
Author

i'm already did that:

export let randomNumbers = (min, max, limit) => new Promise((res, rej) => {
    try {
        let table = [];
        if (max == 0) throw "max must to be a positive number";
        if (max < min) throw "max must to be great than min";
        if (max < limit - 1) throw "max cannot be less than limit";

        for (let i = 0; i < limit; i++) {
            let x = Math.floor((Math.random() * (max - min + 1)) + min);
            if (table.indexOf(x) === -1) table.push(x);
            else i--;
        }
        res(table);
    } catch (e) {
        rej(e);
    }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants