Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active May 27, 2022 20:55
Show Gist options
  • Save sebinsua/873cebd3ee1e9ad450c894be38d99d1f to your computer and use it in GitHub Desktop.
Save sebinsua/873cebd3ee1e9ad450c894be38d99d1f to your computer and use it in GitHub Desktop.
Tagged template literals that throw
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('');
}
@sebinsua
Copy link
Author

Calculations on data with problems can be unsafe. We should look into ways of fixing that, too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment