Last active
May 27, 2022 20:55
-
-
Save sebinsua/873cebd3ee1e9ad450c894be38d99d1f to your computer and use it in GitHub Desktop.
Tagged template literals that throw
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function ordinal(number) { | |
const englishOrdinalRules = new Intl.PluralRules("en", { type: "ordinal" }); | |
const suffixes = { | |
one: "st", | |
two: "nd", | |
few: "rd", | |
other: "th" | |
}; | |
const suffix = suffixes[englishOrdinalRules.select(number)]; | |
return `${number}${suffix}`; | |
} | |
function safe(strings, ...values) { | |
const unsafeIndex = values.findIndex((value) => Number.isNaN(value) || value === undefined || value === null) | |
if (unsafeIndex !== undefined) { | |
throw new Error(`The ${ordinal(unsafeIndex)} value passed into the literal safe\`${strings.flatMap((string, index) => [string, index === unsafeIndex ? `\${${unsafeIndex}}`: values[index]]).join('')}\` was not allowed as it is: ${values[unsafeIndex]}`); | |
} | |
return strings.flatMap((string, index) => [string, values[index]]).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Calculations on data with problems can be unsafe. We should look into ways of fixing that, too.