Skip to content

Instantly share code, notes, and snippets.

@ugate
Created January 2, 2019 21:34
Show Gist options
  • Save ugate/e6ac97a38166586dcdd125ccebe75e7e to your computer and use it in GitHub Desktop.
Save ugate/e6ac97a38166586dcdd125ccebe75e7e to your computer and use it in GitHub Desktop.
/**
* Contitional directive that evaluates each template literal expression for
* [truthiness](https://developer.mozilla.org/en-US/docs/Glossary/Truthy). Each expression that evaluates to a _truthy_
* value will include the string following the expression in the return value. Any string preceding the first expression
* will be included in the result.
* @example
* truthy`${ it.myValue === 123 }
* <div>
* This will be included in the result when <code>myValue === 123</code>
* </div>
* `
* @param {String[]} strs The string passed into template literal tag
* @param {String[]} exps The expressions passed into template literal tag
* @returns {String} The conditional result
*/
function truthy(strs, ...exps) {
var rtn = '';
if (exps[0]) {
for (let i = 0, sln = strs.length, eln = exps.length, ln = Math.max(sln, eln); i < ln; i++) {
rtn += `${strs[i] ? strs[i] : ''}${exps[i] && i !== 0 ? exps[i] : ''}`;
}
}
return rtn;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment