Skip to content

Commit

Permalink
Optimize titleToSlug function (#7073)
Browse files Browse the repository at this point in the history
* Optimize `titleToSlug` function

* Use simpler regex initialization

Co-authored-by: LitoMore <LitoMore@users.noreply.github.com>

* Simpler regex definition

* Run prettier

Co-authored-by: LitoMore <LitoMore@users.noreply.github.com>
  • Loading branch information
mondeja and LitoMore committed Jan 19, 2022
1 parent 8185c5d commit cc64901
Showing 1 changed file with 26 additions and 12 deletions.
38 changes: 26 additions & 12 deletions scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@ import path from 'node:path';
import { promises as fs } from 'node:fs';
import { fileURLToPath } from 'node:url';

const TITLE_TO_SLUG_REPLACEMENTS = {
'+': 'plus',
'.': 'dot',
'&': 'and',
đ: 'd',
ħ: 'h',
ı: 'i',
ĸ: 'k',
ŀ: 'l',
ł: 'l',
ß: 'ss',
ŧ: 't',
};

const TITLE_TO_SLUG_CHARS_REGEX = RegExp(
`[${Object.keys(TITLE_TO_SLUG_REPLACEMENTS).join('')}]`,
'g',
);

const TITLE_TO_SLUG_RANGE_REGEX = /[^a-z0-9]/g;

/**
* Get the slug/filename for an icon.
* @param {Object} icon The icon data as it appears in _data/simple-icons.json
Expand All @@ -26,19 +47,12 @@ export const svgToPath = (svg) => svg.match(/<path\s+d="([^"]*)/)[1];
export const titleToSlug = (title) =>
title
.toLowerCase()
.replace(/\+/g, 'plus')
.replace(/\./g, 'dot')
.replace(/&/g, 'and')
.replace(/đ/g, 'd')
.replace(/ħ/g, 'h')
.replace(/ı/g, 'i')
.replace(/ĸ/g, 'k')
.replace(/ŀ/g, 'l')
.replace(/ł/g, 'l')
.replace(/ß/g, 'ss')
.replace(/ŧ/g, 't')
.replace(
TITLE_TO_SLUG_CHARS_REGEX,
(char) => TITLE_TO_SLUG_REPLACEMENTS[char],
)
.normalize('NFD')
.replace(/[^a-z0-9]/g, '');
.replace(TITLE_TO_SLUG_RANGE_REGEX, '');

/**
* Converts a slug into a variable name that can be exported.
Expand Down

0 comments on commit cc64901

Please sign in to comment.