Last active
February 24, 2024 13:03
-
-
Save liamnewmarch/e23c02b70fb9d5fb6d1e17585c7d9dd1 to your computer and use it in GitHub Desktop.
A (tiny!) tagged template literal function for HTML strings with support for async values
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
/** | |
* Merges multiple arrays using a zip strategy. | |
* | |
* @example ƒ(['a', 'b'], [1, 2, 3]) → ['a', 1, 'b', 2, 3] | |
* @param {...[]} iterables | |
* @yields {*} | |
*/ | |
// | |
function* zipMerge(...iterables) { | |
const length = Math.max(...iterables.map(it => it.length)); | |
for (let i = 0; i < length; i++) { | |
for (const iterable of iterables) { | |
if (i in iterable) yield iterable[i]; | |
} | |
} | |
} | |
/** | |
* Tagged template literal function for HTML strings. | |
* | |
* @example ƒ`1 + 1 = ${Promise.resolve(1 + 1)}` → Promise<'1 + 1 = 2'> | |
* @param {string[]} strings | |
* @param {[]} values | |
* @returns {Promise<string>} | |
*/ | |
export async function html(strings = [], ...values) { | |
return (await Promise.all(zipMerge(strings, values))).join(''); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment