Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active May 27, 2022 20:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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

sebinsua commented Mar 16, 2022

It would also be nice to have a tagged template literal that can handle prefixing numeric values with ~ if they are approximate due to value >= Number.MAX_SAFE_INTEGER || value <= Number.MIN_SAFE_INTEGER and that could apply NumberFormat options using value.toLocaleString.

Maybe a way of passing in a shape like { numberFormatter: 'currency', value: number } for the correct formatters to be used for each data type (allowing this to be typed from a generic createFormattingTag function)?

@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