Previewing HTML files directly on GitHub with a bookmarklet
Published on in Bookmarklets and JavaScript
There's no built-in way to preview HTML files on GitHub, but you can use this nifty bookmarklet. (GitHub's project managers HATE it!)
Published on in Bookmarklets and JavaScript
There's no built-in way to preview HTML files on GitHub, but you can use this nifty bookmarklet. (GitHub's project managers HATE it!)
Content-Type: "application/json"
Published on in JavaScript, Node.js and TypeScript
If you are sending a FormData
body with fetch
,
things might not work correctly if you are (accidentally)
setting the Content-Type
request header to "application/json"
.
mailto:
links with target="_blank"
are surprisingly trickyPublished on in JavaScript
Only because Firefox ignores target="_blank"
in mailto:
links.
Published on in JavaScript
It's too easy to accidentally import a default export with a misleading name.
Published on in JavaScript and TypeScript
Let's learn about anti-symmetry by solving this interview puzzle: "Move all zeros of an array of integers to the end while maintaining the relative order of all non-zeros."
Published on in JavaScript
There's apparently no nice way to bulk-log hours in Jira. Use this One Weird Trick to do it anyway – Jira consultants HATE it!
error.cause
needs to be logged manually to App InsightsPublished on in JavaScript
If you are logging errors to Azure App Insights,
and an Error object has a cause
property (which too could be an Error object),
the cause
Error's message
and stack
properties are not shown in Azure App Insights.
But you can log them manually.
\d
in a regex isn't always equal to [0-9]
Published on in JavaScript and Regular expressions
In JavaScript, \d
and [0-9]
are equal and match only Arabic numerals (the numbers 0–9).
But in some other languages, \d
matches also non-Arabic numerals.
response.json()
can throw an error in JavaScriptPublished on in JavaScript
If the response body is not valid JSON,
response.json()
will throw,
just like JSON.parse()
would throw
if the same data was passed to it.
error.stack
includes the error message in some JS environmentsPublished on in JavaScript
Last updated on
In V8-based JS environments (e.g. Chrome, Deno and Node.js) and in Bun,
error.stack
= error class name + error.message
+ stack frames.
yarn install
failing mysteriously on Node.js v18.18Published on in JavaScript
Last updated on
TL;DR: Upgrading Yarn from v1 to v4 fixed it for me.
Published on in JavaScript and Mnemonics
When sorting an array with a custom comparator function,
the function should return <0
, 0
or >0
.
But what do the values do?
Use this weird visual mnemonic –
sorting consultants HATE it!
Published on in JavaScript, TypeScript and Zod
Alternative title:
I finally found a good use case for z.object().strict()
in Zod.
Published on in ESLint, JavaScript and TypeScript
Last updated on
Node-Cache (a JS library) has generic get
and set
methods,
but it's easy to accidentally misuse them.
I made a type-safer wrapper around the library.
Published on in Bookmarklets and JavaScript
Quick and dirty code to grab a single frame of a YouTube video. Might work with other video players too.
Date
objects are nicer to work with than date stringsPublished on in JavaScript, TypeScript and Zod
When parsing data,
date strings should likely be converted to Date
objects.
But beware mutations.
Published on in JavaScript, Joi, TypeScript and Zod
Last updated on
Parsing encompasses validation, plus it can increase type-safety, plus it can transform the data to a better format. Parse, don't just validate.
Published on in JavaScript and SendGrid
If you send a single email to a bunch of email addresses, and some of the addresses are aliases, i.e. they point to the same email inbox, chances are high that only one copy of the email is delivered to that inbox.
Published on in JavaScript and TypeScript
Last updated on
A little helper function to retry a function automatically a limited number of times (or until success) and with a certain delay between retries. Useful e.g. when working with a flaky API.
Published on in JavaScript and React
Last updated on
If I'm already displaying data that I have successfully fetched with SWR, and then another fetch call fails (when revalidating the data), I don't want to replace the data view with an error view. Here's how to avoid that.
React.forwardRef
Published on in JavaScript and React
A component wrapped in React.forwardRef
normally expects to receive a ref from its parent component.
What if you want the component to have a ref
even if it doesn't receive one from its parent?
Published on in JavaScript
"Given an array of coins and a target amount, return all combinations of coins that add up to the amount, or an empty array if no such combinations exist."
Published on in Clean code and JavaScript
For example, mutating a reducer function's accumulator array can be better than religiously avoiding mutations and returning only new arrays from the reducer.
Published on in JavaScript
Last updated on
That's because it would take a very long time, and at some point you would have so many permutations that they wouldn't fit in an array.
Published on in JavaScript
Last updated on
Example:
converting [1, 2, 3]
into [[1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]
.
Published on in JavaScript
Instead of spending 5 minutes to look for and use an existing mortgage calculator, I wasted time figuring out how to do the calculations from scratch.
Published on in JavaScript and TypeScript
Huh. But if the array has 2+ items, attempting to sort it will cause a TypeError.
useReducer
Published on in JavaScript and React
Say goodbye to useState
and a silly toggler function calling the state setter.
Be cool and use a tiny reducer instead.
Published on in JavaScript, Mithril.js and React
AutoAnimate is a JS library that provides simple animations with no effort. Works with Mithril.js, React and any other JS app.
type="button"
Published on in JavaScript, React and TypeScript
A <button>
element defaults to type="submit"
which can cause accidental form submissions.
Make type="button"
the default in your Button component
to make your life easier.
Published on in JavaScript and TypeScript
The TypeScript compiler could help prevent "illegal invocation" errors at compile time, at least theoretically.
dangerouslySetInnerHTML
Published on in JavaScript, React and TypeScript
Last updated on
To handle internal link clicks when using dangerouslySetInnerHTML
,
attach click event listeners to the rendered links.
In the listener, push the link to the browser history.
conditional()
Published on in JavaScript, Joi and Testing
Last updated on
Use { is: Joi.any().valid(...values) }
to check if a value is included in an array.
.mts
is a cool file extension (TypeScript ES modules)Published on in JavaScript, Node.js and TypeScript
What's that, a file extension named after me?! Or a file extension for TypeScript files that are always ES modules?
Published on in JavaScript and React
React is marketed as a view library, but it's more accurately a (view component) framework.
compose()
is right-to-leftPublished on in JavaScript
Functions composed together with compose()
are called from right to left.
It feels unintuitive at first,
but it's conventional
and kind of makes sense.
Published on in JavaScript, Mithril.js, Rant and React
Last updated on
React's ecosystem is large, which is a good thing: lot's of great libraries to use. But it's also a bad thing: most of those libraries are compatible only with React.
Published on in JavaScript and React
Last updated on
HTM provides a transpiler-free alternative to JSX via tagged templates. HTM has some limitations, but can be used in browsers and can be good for smaller projects.
Published on in JavaScript
Fun way to solve the simple puzzle.
Infinitely repeating arrays
and mapping over multiple arrays
almost makes the remainder/modulo operator (%
) unnecessary.
Published on in JavaScript and TypeScript
Using recursion,
logical OR assignment operator (||=
),
BigInts
and more!
Published on in Episerver, JavaScript and React
Last updated on
Also known as Episerver/Idio Content Recommendations. The usual way of using a Mustache template can be circumvented by using a JavaScript proxy.
Published on in JavaScript and Node.js
Last updated on
Say goodbye to ../
times million
and use absolute import paths from the app's root directory instead.
Two contenders: Basetag and Sultan's sexy-require
! 🤺
Published on in JavaScript, React and TypeScript
Last updated on
I.e. props that depend on other props. You can require and forbid certain prop combinations by utilizing TypeScript's union and intersection types.
useStateMachine
: ½ kB state machine hook for ReactPublished on in JavaScript and React
A state machine is a bit like useReducer
,
but with greater constraints (in a good way).
This state machine hook is tiny.
Published on in JavaScript and React
A common solution is to scroll to top every time the page changes. That's incorrect: the page should be scrolled to top only when navigating to new pages, not when navigating back or forward.
Published on in JavaScript and React
Normally you would use one-way data binding in React apps: parent components own data and pass it to children. You can mimic two-way data binding with a custom hook.
Published on in Clean code, JavaScript and React
Last updated on
A multi-site React project has likely two kinds of components: common components and site-specific components. There are a few ways to handle site-specific logic in common components.
Published on in ESLint and JavaScript
There's an ESLint rule to prevent importing certain files in certain folders. I needed this in a multi-site project to prevent importing site-specific components in other sites' folders.
length
propertyPublished on in JavaScript
Last updated on
A bit exotic, but can be useful for currying.
Published on in JavaScript, React and Testing
React context is normally updated inside the React app. Here's a hacky way how I circumvented that restriction in a test file.
Published on in JavaScript and TypeScript
"Parameter properties" reduce boilerplate in classes, but they can also make the code hard to read.
Published on in JavaScript
Spoiler:
new Date(year, 1, 29).getDate() === 29
.
Published on in JavaScript, React and Testing
Such naming helps you create tests that resemble the way your users use your app.
Published on in Accessibility, JavaScript, React and Testing
Accessible queries take into account the semantic meaning of HTML elements. Such queries help you write more accessible apps.
Published on in JavaScript and Mithril.js
Last updated on
Create a DocumentFragment
and render the component to it.
Then there's no need to mount the component to the DOM.
Published on in JavaScript and Mithril.js
Last updated on
Disable auto-redraw with event.redraw = false
and use a timeout.
Published on in JavaScript and Mithril.js
Last updated on
m.nest('ul > li', 'Item')
can be achieved with reduceRight()
.
Intl.ListFormat
Published on in JavaScript
Last updated on
Pass an array of strings and get back a string with the array items separated by commas, except with the last comma replaced with the word "and" or "or." Like "item 1, item 2 and item 3."
Published on in Episerver, JavaScript and React
Thoughts on how to efficiently use React to render Episerver blocks embedded in TinyMCE fields.
Published on in JavaScript
Last updated on
Run JSON.stringify(object, null, 2)
.
Adjust the number for a different level of indentation.
Published on in JavaScript and Regular expressions
Last updated on
How to convert
'/foo/bar/baz/'
into an array of
'/'
, '/foo/'
, '/foo/bar/'
, and '/foo/bar/baz/'
.
Example use case: building breadcrumb navigations.
new Date()
and Date.parse()
are bad at parsing datesPublished on in JavaScript
Last updated on
Use them only with certain date time formats, and use a library for parsing fancy formats.
Published on in JavaScript
Last updated on
The error is thrown when calling a function
whose this
keyword isn't referring to the object where it originally did,
i.e. when the "context" of the function is lost.
array.shift()
vs array.unshift()
in JavaScriptPublished on in JavaScript and Mnemonics
Last updated on
shift()
removes the first array item,
and unshift()
prepends items to the array.
But how to remember which is which?
toLocaleString()
in Node.jsPublished on in JavaScript and Node.js
Last updated on
With Node.js 13+,
it should just work.
With earlier Node.js versions,
you need to install and use the full-icu
package.
Published on in Clean code, CSS and JavaScript
Last updated on
These two similar principles state that the behavior of code should be obvious on inspection and that code should be located where it's relevant.
Published on in JavaScript
JavaScript doesn't provide a native way to get the week number of a date. Just use a library instead.
Published on in JavaScript and Regular expressions
Last updated on
E.g. how to capture overlapping pairs of letters from the string 'abcde'
,
i.e. 'ab'
, 'bc'
, 'cd'
and 'de'
.
Spoiler: with lookahead and lookbehind assertions.
fn.apply()
vs fn.call()
in JavaScript + better alternativePublished on in JavaScript and Mnemonics
Last updated on
Mnemonic:
"a" (apply()
) for an array,
"c" (call()
) for commas.
But Reflect.apply()
is better.
Published on in JavaScript and React
Last updated on
If you need form input values only at the time of form submission, uncontrolled inputs can be nice to work with.
Published on in JavaScript
Last updated on
My quick notes on a funny but informative video (11:27) that explains how tail call optimization (TCO) works. Bonus: does JS support TCO? Spoiler: yes but no.
package.json
automaticallyPublished on in JavaScript
Last updated on
Just run npx sort-package-json
.
Published on in JavaScript
Last updated on
A simple reducer to chunk (split) an array into smaller arrays.
Published on in C#, Episerver and JavaScript
Requests with the Accept
header set to application/json
are automatically routed to Content Delivery API.
Here's how to bypass it
and make the request go to a page controller instead.
Published on in JavaScript, Mithril.js and React
Last updated on
JSX is just JS under the hood.
Hyperscript is like that JS,
but better.
Example:
h('a.link', { href }, 'Click me')
is nicer than
<a className="link" href={href}>Click me</a>
,
right? Right?!
default
doesn't have to be the last casePublished on in C#, Clean code, JavaScript and TypeScript
Last updated on
Non-last default
cases are confusing
but perfectly valid.
Sometimes it makes sense to place them at the beginning or in the middle.