Skip to content

Instantly share code, notes, and snippets.

@sneppy
Created April 27, 2020 19:06
Show Gist options
  • Save sneppy/ec0c3384702b0d67c1b18392cd34b610 to your computer and use it in GitHub Desktop.
Save sneppy/ec0c3384702b0d67c1b18392cd34b610 to your computer and use it in GitHub Desktop.
sprintf for JavaScript
/**
*
*/
String.prototype.format = function formatString(...subs) {
// String tag functions
// @ref https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const formatter = (strings, ...keys) => {
return (...values) => {
let dict = values[values.length - 1] || {}
let res = [strings[0] || '']
keys.forEach((key, i) => {
let val = Number.isInteger(key) ? values[key] : dict[key]
res.push(val, strings[i + 1])
})
return res.join('')
}
}
// Dispatch a dynamic built function
// What a joke JavaScript ...
return Function('f', '...x', 'return f`' + this + '`(...x)').call(null, formatter, ...subs)
}
// Ex.
// let fmt = 'Hello ${0}!'
// let s0 = fmt.format('world')
// let s1 = fmt.format(1024)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment