Skip to content

Commit

Permalink
Optimize for loop with single pass regex
Browse files Browse the repository at this point in the history
  • Loading branch information
JoelBCarter committed Sep 4, 2024
1 parent 0a2f87b commit 78e9101
Showing 1 changed file with 13 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@ import { XnsNamePublicValidators } from '../validation/index.ts'

export type ValidSourceTypes = 'xnsName' | 'hash' | null

// Escaping special regex characters in the disallowed keys
const escapeRegex = (str: string) => str.replaceAll(/[$()*+.?[\\\]^{|}]/g, String.raw`\$&`)

// Escaping and then creating the regex
const disallowedCharsPattern = Object.keys(DisallowedModuleIdentifierCharacters)
.map(escapeRegex)
.join('')
// Creating the final regex
const REMOVE_DISALLOWED_CHARS = new RegExp(`[${disallowedCharsPattern}]`, 'g')

export class XnsNameHelper {
static ValidTLDs = ['.xyo'] as const

Expand Down Expand Up @@ -83,17 +93,15 @@ export class XnsNameHelper {
// convert to lowercase
const lowercaseXnsName = str.toLowerCase()

// remove everything except letters, numbers, and dashes
// Remove everything except letters, numbers, and dashes
let formattedXnsName = lowercaseXnsName.replaceAll(/[^\dA-Za-z-]+$/g, '')

// remove leading and trailing dashes
// Remove leading and trailing dashes
formattedXnsName = formattedXnsName.replaceAll(/^-+|-+$/g, '')

// Filter out disallowed characters.
// NOTE: not necessary because of the regex/replacement above, but leaving for when certain special characters become allowed
for (const c of Object.keys(DisallowedModuleIdentifierCharacters)) {
formattedXnsName = formattedXnsName.replaceAll(c, '')
}
formattedXnsName = formattedXnsName.replaceAll(REMOVE_DISALLOWED_CHARS, '')

return formattedXnsName
}
Expand Down

0 comments on commit 78e9101

Please sign in to comment.