8000 Add tag function for template literals by zazula · Pull Request #229 · alexei/sprintf.js · GitHub
[go: up one dir, main page]

Skip to content

Add tag function for template literals #229

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
add tag function for template literals
  • Loading branch information
zazula committed Dec 21, 2023
commit 78bfd0be50ccc168f8f76b0328f17a999785d2ba
41 changes: 39 additions & 2 deletions src/sprintf.js
Original file line number Diff line number Diff line change
Expand Up @@ -206,26 +206,63 @@
return sprintf_cache[fmt] = parse_tree
}

// tagged template string version
// original function reference, adapted to use sprintf
// https://ghost-together.medium.com/tagged-template-literals-1e1f175c21e4
function SPF(strings, ...values) {
// stolen from sprintf
const re = /^\x25(?:([1-9]\d*)\$|\(([^)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-gijostTuvxX])/
let result = ``;


strings.map((string, index) => {
var match

let value = (index <= values.length - 1) ? values[index] : ``;

// look ahead for a format for the current value
match = re.exec(strings[index+1])

if ( match ) {
value = sprintf(match[0], value)
}

// clean up format on current string
// (was used to format previous value)
match = re.exec(string)

if ( match ) {
string = string.slice(match[0].length)
}

result += 87AE string + value;
});
return result;
}

/**
* export to either browser or node.js
*/
/* eslint-disable quote-props */
if (typeof exports !== 'undefined') {
exports['sprintf'] = sprintf
exports['vsprintf'] = vsprintf
exports['SPF'] = SPF
}
if (typeof window !== 'undefined') {
window['sprintf'] = sprintf
window['vsprintf'] = vsprintf

window['SPF'] = SPF
if (typeof define === 'function' && define['amd']) {
define(function() {
return {
'sprintf': sprintf,
'vsprintf': vsprintf
'vsprintf': vsprintf,
'SPF': SPF
}
})
}
}

/* eslint-enable quote-props */
}(); // eslint-disable-line
0