Skip to content

Instantly share code, notes, and snippets.

@sebinsua
Last active Mar 16, 2022
Embed
What would you like to do?
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)?

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