I have a JavaScript function that is supposed to take in person's first and last name and generate a unique abbreviation. Examples:
Michael Scott -> scmi1
Michelle Scrambledeggs -> scmi2
Genghis Khan -> khge1
Inside this function, I nested a recursive function that is supposed to find a suffix number that is not taken, but I can't get it to return proper value. Here's the code:
/**
* Generates a abbreviation from customer's first and last name
* by combining last name's first two letter with first name's first two letters
* @param {string} firstName
* @param {string} lastName
* @returns {string} abbreviation, for example person named John Smith will have short: 'smjo1'
*/
const generateShort = async (firstName, lastName) => {
// Concatenate last name's two first letters with first name's two first letters
var short = lastName.substring(0, 2) + firstName.substring(0, 2)
short = short.toLowerCase()
// At the end of each short, add a number
// So that each abbreviation can be unique
async function findFreeSuffix(suffix_number) {
var final_short = short + suffix_number
// Scan the database in search for person with this short
window.api.searchClientExact(final_short).then(res => {
if (res.length > 0) {
// If this abbreviation is taken...
findFreeSuffix(suffix_number + 1)
} else {
console.log(suffix_number) // <- This prints the correct result, but I'm unable to return it
return suffix_number
}
})
}
const suffix = await findFreeSuffix(1)
// Suffix is undefined :(
return short + suffix
}