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
It would also be nice to have a tagged template literal that can handle prefixing numeric values with
~
if they are approximate due tovalue >= Number.MAX_SAFE_INTEGER || value <= Number.MIN_SAFE_INTEGER
and that could applyNumberFormat
options usingvalue.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 genericcreateFormattingTag
function)?