Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active February 29, 2024 21:36
Show Gist options
  • Select an option

  • Save lewdev/de750860208f03cc6d4037a12b3b3763 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/de750860208f03cc6d4037a12b3b3763 to your computer and use it in GitHub Desktop.
⛳ I Code Golfed Somebody Else's Dweet

⛳ I Code Golfed Somebody Else's Dweet

I'm hoping this is interesting to somebody out there that likes code golfing or is interested in knowing what it looks like.

I saw a dweet with a lot of parts that I could add code golf techniques to. I was able to reduce the dweet from 150 to 131 bytes; a 19-byte reduction of code that does the same thing.

I golfed this (150b):

x.font="108pt _";x.fillStyle="#ffffff22";x.fillRect(0,0,1920,1080);x.fillStyle="#000";onmousemove=e=>x.fillText("dwitter",e.offsetX*3.1,e.offsetY*3.1)

To this (131b):

x.font="2in _";f=a=>x.fillStyle=a;f`#ffffff22`;x.fillRect(0,0,2e3,2e3);f`#000`;onmousemove=e=>x.fillText("dwitter",e.x*3.1,e.y*3.1)

👨‍💻 The Techniques

👉 Technique 0: Use alternative font size values

Before I discovered dweeting, I never knew there were other font values besides pt and px. There's also cm and in.

in was more useful since we want to use a single-digit value to make the font huge text.

So I changed x.font="108pt _"; to x.font="2in _"; which saved 2 characters.

👉 Technique 1: Turn fillStyle into a method

When fillStyle is used more than once, it's useful to put it into a method like this: f=a=>x.fillStyle=a so that it can accept a single string argument that can be called like this:

f`#ffffff22`

Which sets the fill color to an opaque white. The last 2 hex values is the opacity value.

This saved 5 characters.

👉 Technique 2: Calling a method with a single string argument doesn't need parenthesis

This is already demonstrated in the above Technique 1. But basically, these two things are the same thing:

f("#000")
//and
f`#000`

This reduces each method call by 2 characters.

👉 Technique 3: Use rounded up values with e notation.

OP used this x.fillRect(0,0,1920,1080); to clear the background, but since it doesn't have to fit exactly the size of the canvas, using bigger values and less text was okay in this instance. And changed it to:

x.fillRect(0,0,2e3,2e3)

This reduced it by 2 characters.

👉 Technique 4: Using shorter mouse coodinate attributes that do the same thing (offsetX vs x)

I looked at other dweets and saw that people didn't have to use offsetX and offsetY to get the mouse coodinates, but just x and y saving 12 characters which was huge.

Code golf is fun to me because it demonstrates how you can do more with less. There are more techniques I could share but I just wanted to keep this short.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment