logoalt Hacker News

varenclast Friday at 8:14 PM3 repliesview on HN

TIL that

   js_func`string`
is valid JS and calls `js_func` as a tagged template literal, passing it a TemplateStringsArray. Going to use "console.log`weeee`" in my code now.

Replies

jsheardlast Friday at 8:34 PM

It's not common but few libraries use that to support JSX-like syntax at runtime, without a build step.

e.g. https://github.com/developit/htm and https://lit.dev/docs/components/rendering/

Lerclast Friday at 9:43 PM

I recently used the feature in a code embedded image generator so I could have compact images store tiny images in inline code.

https://gisthost.github.io/?8d537c4a3b2331e7c6c45d31f1900330

The Trashcan in that sampler is stored as

    TRASH: Q`!B>#Z>!F>#F:V:V>!>B#^BZfBf3`

decoded to a SVG D path by

    function Q([e]){let c,t,n,d="",l=0,o=c=>e.charCodeAt(l++)-33;for(;l<e.length;d+=t<20?(c=1&t?100:10,"MmLlHhVvCcSsQqTtAaZz"[t]):t<71?t-45+" ":71==t?(n=o(),e.slice(l,l+=n)):(94*(t-72)+o()-1033)/c+" ")t=o();return d}
which can be turned into an image by

    function simpleImage(p="M-22 -22 h44 v44 h-44 Z",w=64,h=w,o={}){let{background:b="#0000",stroke:s="#000f",fill:f="#fffa",thickness:t=w/32,transform:m=[1,0,0,1,0,0],scale:c=1,angle:a=0}=o;const C=new OffscreenCanvas(w,h),X=C.getContext("2d");let P=new Path2D(p);m instanceof DOMMatrix||(m=new DOMMatrix(m));m.translateSelf(w/2,h/2);m.rotateSelf(a);m.scaleSelf(c,c);let T=new Path2D;T.addPath(P,m);P=T;X.fillStyle=b;X.fillRect(0,0,w,h);X.fillStyle=f;X.strokeStyle=s;X.lineWidth=t;X.stroke(P);X.fill(P);return C}


The Sampler contains all of the images in the html file and still comes out to be only 13k. Probably quite a bit less if you removed the ray tracer and scenes.
show 1 reply
rrileylast Friday at 10:04 PM

Niiice! I finally understand the origin of this JS syntax used in SQL queries and GraphQL:

sql`SELECT * FROM users WHERE id = ${userId}`

const q = gql` query GetUser { user(id: ${userId}) { name email } } `;