The code below is my first purpose built asynchronous recursive function. It took me a while to figure out how to write the thing, and I would like a second opinion. It's part of a project for The Odin Project, a simple book log. I don't have the site live yet, I want to implement a few more features first. I was hoping that you all could take a look at it and let me know what I did right and what I did wrong.
The purpose is to create a unique ID for a book when it is created, by first generating the possible ID, then checking it against the given array of books currently in play.
const randomNum = (minNum, maxNum) => {
const min = Math.ceil(minNum);
const max = Math.floor(maxNum);
return Math.floor(Math.random() * (max - min) + min);
};
const letters = 'ABCDEFGHIJKLMNPRSTUVWXYZ';
const generateId = () => {
return `${letters[randomNum(1, 24)]}${randomNum(1000, 9999)}`;
};
const makeId = async (checkedArray) => {
const newId = generateId();
if (!checkedArray.includes(newId)) {
return Promise.resolve(newId);
}
const recursiveResult = await new Promise((resolve, reject) => {
if (checkedArray) {
resolve(makeId(checkedArray));
} else {
reject('makeId failed');
}
});
return recursiveResult;
};
The biggest hang up that I ran into was where to put the successful result's return statement. I wanted to get this without asking for help, so it took me a couple of days worth of research. I finally found out about how and when to return a Promise.resolve() and with happy abandon I implemented it.
And I have to say, figuring it out myself was immensely satisfying!
One alternative that I came up with was to use the current date. But I felt that while it worked, it wasn't an ideal solution... Unless it was...
const altId = (bookTitle) => {
return `${bookTitle.replace(/\s/g, '')}${Date.now()}`;
};
letters
is not scoped correctly \$\endgroup\$async
? \$\endgroup\$