Skip to content

Commit

Permalink
refactor(util): extract color name deduplication into separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
pawcoding committed Aug 16, 2024
1 parent 394c5ce commit c254365
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
25 changes: 25 additions & 0 deletions src/app/shared/utils/deduplicate-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { normalizeName } from './normalize-name';

/**
* Deduplicate a name by adding a number to the end if it already exists.
*/
export function deduplicateName(name: string, existingNames: Array<string>): string {
const normalizedNames = existingNames.map((n) => normalizeName(n));

// Check if name already exists
while (normalizedNames.includes(normalizeName(name))) {
// Check if the name already has a number
const lastNumber = name.match(/\d+$/);
if (lastNumber) {
// Increment the number
const number = parseInt(lastNumber[0], 10);
name = name.replace(/\d+$/, '') + (number + 1);
} else {
// Add a number to the color name
name += ' 2';
}
}

// Return the deduplicated name
return name;
}
14 changes: 2 additions & 12 deletions src/app/view/view.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { ToastService } from '../shared/data-access/toast.service';
import { TrackingEventAction, TrackingEventCategory } from '../shared/enums/tracking-event';
import { Color, Shade } from '../shared/model';
import { NoPaletteComponent } from '../shared/ui/no-palette/no-palette.component';
import { deduplicateName } from '../shared/utils/deduplicate-name';
import { IS_RUNNING_TEST } from '../shared/utils/is-running-test';
import { sleep } from '../shared/utils/sleep';
import { ViewPaletteComponent } from './ui/view-palette/view-palette.component';
Expand Down Expand Up @@ -242,18 +243,7 @@ export default class ViewComponent implements OnInit, UnsavedChangesComponent {

// Check if color name already exists
const colorNames = palette.colors.map((c) => c.name);
while (colorNames.includes(color.name)) {
// Check if the color name already has a number
const lastNumber = color.name.match(/\d+$/);
if (lastNumber) {
// Increment the number
const number = parseInt(lastNumber[0], 10);
color.name = color.name.replace(/\d+$/, '') + (number + 1);
} else {
// Add a number to the color name
color.name += ' 2';
}
}
color.name = deduplicateName(color.name, colorNames);

// Add the color to the palette
palette.addColor(color);
Expand Down

0 comments on commit c254365

Please sign in to comment.