Skip to content

Instantly share code, notes, and snippets.

@Phoenix35
Last active May 26, 2018 20:09
Show Gist options
  • Save Phoenix35/f5950719047b3f1af91936b990965605 to your computer and use it in GitHub Desktop.
Save Phoenix35/f5950719047b3f1af91936b990965605 to your computer and use it in GitHub Desktop.
Gist of tags for template literals to 'pretty format' numbers
/* Use:
dec`1_234.5` // >> 1234.5
oct`1_234` // >> 0o1234 === 668
bin`0110_1100` // >> 0b01101100 === 108
hex`A2_34` // >> 0xA234 === 41524
*/
// Heavily based on code by "Kusu"
const templateJoin = (strings, placeholders) => {
const regex = /_/gu
let result = strings[0]
// DO NOT
// I repeat
// DO NOT use forEach
// Use for (const [placeholder, i] of placeholders.entries())
placeholders.forEach((placeholder, i) => {
result += placeholder + strings[++i]
})
return result.replace(regex, ``)
}
const hex = ((strings, ...placeholders) =>
Number(`0x${templateJoin(strings, placeholders)}`)
)
const dec = ((strings, ...placeholders) =>
Number(templateJoin(strings, placeholders))
)
const oct = ((strings, ...placeholders) =>
Number(`0o${templateJoin(strings, placeholders)}`)
)
const bin = ((strings, ...placeholders) =>
Number(`0b${templateJoin(strings, placeholders)}`)
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment