Skip to content

Commit

Permalink
performance improvement
Browse files Browse the repository at this point in the history
  • Loading branch information
aeltorio committed Nov 3, 2024
1 parent 974168f commit 6deaeeb
Showing 1 changed file with 26 additions and 5 deletions.
31 changes: 26 additions & 5 deletions username_generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,30 @@ export function normalize(name: string): string {
return name.normalize("NFD").replace(/'/g,"_").replace(/ /g,"_").replace(/[\u0300-\u036f]/g, "").toLowerCase();
}

/**
* Precompute the cumulative sums for the given data
* @param data the data to precompute cumulative sums for
* @returns the cumulative sums
*/
export function precomputeCumulativeSums(data: (Firstname | Lastname)[]): number {
return data.reduce((sum, current) => sum + current.occurrences, 0);
}

/**
* Returns a random first name from the array ponderated by the occurrences
* @param data the firstnames data
* @param precomputedTotal the precomputed total number of occurrences
* @returns a random firstname
*/
export function randomFirstnamePonderated(data: Firstnames): string {
export function randomFirstnamePonderated(data: Firstnames, precomputedTotal: number | undefined): string {
// compute the total number of occurrences
const total = data.firstnames.reduce((sum, current) => sum + current.occurrences, 0);
let total = 0;
if (precomputedTotal === undefined) {
total = precomputeCumulativeSums(data.firstnames);
} else {
total = precomputedTotal;
}


// Generate a random number between 0 and total
const randomValue = Math.floor(Math.random() * total);
Expand All @@ -61,9 +77,14 @@ export function randomFirstnamePonderated(data: Firstnames): string {
* @param data the lastnames data
* @returns a random lastname
*/
export function randomLastnamePonderated(data: Lastnames): string {
export function randomLastnamePonderated(data: Lastnames, precomputedTotal: number | undefined): string {
// compute the total number of occurrences
const total = data.lastnames.reduce((sum, current) => sum + current.occurrences, 0);
let total = 0;
if (precomputedTotal === undefined) {
total = precomputeCumulativeSums(data.lastnames);
} else {
total = precomputedTotal;
}

// Generate a random number between 0 and total
const randomValue = Math.floor(Math.random() * total);
Expand All @@ -87,5 +108,5 @@ export function randomLastnamePonderated(data: Lastnames): string {
* @returns a random username
*/
export function generateUsername(firstnames: Firstnames, lastnames: Lastnames): string {
return `${normalize(randomFirstnamePonderated(firstnames))}.${normalize(randomLastnamePonderated(lastnames))}`;
return `${normalize(randomFirstnamePonderated(firstnames,undefined))}.${normalize(randomLastnamePonderated(lastnames,undefined))}`;
}

0 comments on commit 6deaeeb

Please # to comment.