Snippets about js
23 snippets
-
SNP 132
#935
Lerp and clamp
Two one-liners every game and animation ends up needing.
-
SNP 129
#513
Crisp pixel art on a canvas
The canvas smooths scaled sprites too. Turn it off, in two places.
-
SNP 122
#42A
Load .env files in Node without a package
dotenv is built into Node now.
-
SNP 121
#471
Compute page data in beforeAll, not beforeRender
A Stati hook that writes front matter in beforeRender makes those pages rebuild on every build.
-
SNP 102
#512
Seeded random numbers in JavaScript
Math.random() can't be seeded. For procedural levels you need one that can.
-
SNP 099
#A51
Clean up event listeners in useEffect
The resize listener that stayed alive after the component was gone, and how to not do that.
-
SNP 084
#45A
__dirname in ES modules
It's gone in ESM. Here is the replacement, and the newer, nicer one.
-
SNP 079
#B41
v-model on your own component with defineModel
Vue 3.4 made two-way binding on custom components a one-liner.
-
SNP 076
#614
Environment variables in Nuxt
Runtime config, the NUXT_ prefix and which values end up in the browser.
-
SNP 072
#935
Do something when an element scrolls into view
Lazy loading, fade-ins and "read" markers without a scroll listener.
-
SNP 067
#694
Redirect from a route middleware in Nuxt
Send people who aren't logged in to the login page before the page even renders.
-
SNP 061
#351
Format dates without a library
Intl.DateTimeFormat does most of what you used moment or date-fns for.
-
SNP 056
#496
Group an array by a key
Object.groupBy is finally a thing. Here it is, with the fallback for older runtimes.
-
SNP 052
#25A
Fetch with a timeout
fetch() waits forever by default. Give up after a few seconds.
-
SNP 042
#2B4
Shuffle an array properly
The sort(() => Math.random() - 0.5) trick is biased. Fisher-Yates is just as short and actually random.
-
SNP 038
#416
Read a JSON file in Node
Two ways, one of them without any fs code at all.
-
SNP 036
#B63
Sleep in Node without writing a timeout function
Node ships a promise-based setTimeout, so the little helper from my old snippet isn't needed there.
-
SNP 034
#6B1
Watch a nested property in Vue
Your watcher doesn't fire when something deep inside an object changes. Here is why and what to do.
-
SNP 031
#592
Copy text to the clipboard
The modern clipboard API in three lines, with the gotchas.
-
SNP 022
#B31
Debounce a function in plain JavaScript
Run a function only after the user stopped typing, without pulling in a library for it.
-
SNP 015
#B96
Create timeout in an async function
To throttle the execution of our async function we will create a timeout method.
-
SNP 013
#249
Get query parameters in Nuxt
Read the GET request query parameters in your code.
-
SNP 003
#24B
Select all text in input field on click the Vue JS way
Comparing the traditional javascript way with the Vue event you can use.