DEV Community

Discussion on: 30 JavaScript Tricky Hacks

Collapse
 
jdhinvicara profile image
John Harding

Cool! I never knew about #11. It took me a while to figure it out - and, as another poster (@joolsmcfly) mentioned, your example just returns the same string you passed in. However, the sample he provided has an empty span at the end and doesn't use reduce...

So, here's my submission as a better example (which is entirely subjective of course):

const spanify = (strings, ...values) => 
  strings.reduce((resultSoFar, stringPart, valueIndex) => 
    `${resultSoFar}${stringPart}${values[valueIndex]?`<span class='foo'>${values[valueIndex]}</span>`:''}`, '')

spanify`My name is ${'John'}` // "My name is <span class='foo'>John</span>"
Enter fullscreen mode Exit fullscreen mode