Skip to content

Instantly share code, notes, and snippets.

@tkrotoff
tkrotoff / #mockWindowLocation.ts
Last active March 14, 2024 16:39
Jest/Vitest mocks for JSDOM window.location & window.history
/* eslint-disable unicorn/no-null */
/*
* Resetting window.location between tests is unfortunately a hard topic with JSDOM.
*
* https://gist.github.com/tkrotoff/52f4a29e919445d6e97f9a9e44ada449
*
* FIXME JSDOM leaves the history in place after every test, so the history will be dirty.
* Also its implementations for window.location and window.history are lacking.
* - https://github.com/jsdom/jsdom/blob/22.1.0/lib/jsdom/living/window/Location-impl.js
@tkrotoff
tkrotoff / git-staged-warn-binaries.sh
Last active August 10, 2023 08:51
Warns about Git staged binary files
#!/usr/bin/env sh
# Warns about Git staged binary files
# https://gist.github.com/tkrotoff/dc49a8e501b6fdea5a4b66301f7682fc
# Capture the output of "git diff" in a temporary file
tmpfile=$(mktemp)
# https://stackoverflow.com/q/28109520
git diff -z --staged --name-only --diff-filter=ACMR > "$tmpfile"
@tkrotoff
tkrotoff / #deepFreeze.ts
Last active April 18, 2024 08:44
Deeply freezes an object
import { ReadonlyDeep } from 'type-fest';
/**
* Deeply freezes an object by recursively freezing all of its properties.
*
* - https://gist.github.com/tkrotoff/e997cd6ff8d6cf6e51e6bb6146407fc3
* - https://stackoverflow.com/a/69656011
*
* FIXME Should be part of Lodash: https://github.com/Maggi64/moderndash/issues/139
*
@tkrotoff
tkrotoff / #FormValidationErrorMessageHack.tsx
Last active June 18, 2023 10:29
I want an error tooltip on a button when clicked, let's use the browser native input validation error message
import { forwardRef } from 'react';
// ref is optional with forwardRef(), I want it to be mandatory
// type ... = ReturnType<typeof forwardRef<T, P>>;
type ForwardMandatoryRefComponent<T, P> = React.ForwardRefExoticComponent<
React.PropsWithoutRef<P> & React.RefAttributes<T> & { ref: React.Ref<T> }
>;
type Props = {
// Why? https://stackoverflow.com/a/25367640
@tkrotoff
tkrotoff / #ObjectValues.ts
Last active June 18, 2023 08:42
Recursively converts all values from null to undefined and vice versa
/* eslint-disable guard-for-in, @typescript-eslint/ban-types, @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-assignment */
import { Primitive } from 'type-fest';
// [Generic way to convert all instances of null to undefined in TypeScript](https://stackoverflow.com/q/50374869)
// ["I intend to stop using `null` in my JS code in favor of `undefined`"](https://github.com/sindresorhus/meta/discussions/7)
// [Proposal: NullToUndefined and UndefinedToNull](https://github.com/sindresorhus/type-fest/issues/603)
// Types implementation inspired by
@tkrotoff
tkrotoff / #getRandomNumber.ts
Last active April 9, 2024 14:39
getRandomInt() & getRandomFloat()
// https://gist.github.com/tkrotoff/f3f36926edeeb3f4ce4411151bde37b2
// Exported for testing purposes only
// https://stackoverflow.com/a/45736131
export function getNumberWithDecimalPlaces(num: number, decimalPlaces: number) {
const power = 10 ** decimalPlaces;
return Math.floor(num * power) / power;
}
type GetRandomNumberOptions = {
@tkrotoff
tkrotoff / #assert.ts
Last active August 3, 2023 23:13
TypeScript friendly assert
/**
* Writes an error message to the console if the assertion is false.
*
* If the assertion is true, nothing happens.
*
* If your code only runs in Node.js, prefer `import { strict as assert } from 'node:assert'`
* because it throws.
*
* https://gist.github.com/tkrotoff/1a216f376cb4fba5bc7d8b5109c3a32e
* https://devblogs.microsoft.com/typescript/announcing-typescript-3-7/#assertion-functions
@tkrotoff
tkrotoff / #RouterProgressBar.tsx
Last active May 14, 2023 22:55
Progress bar like NProgress in 90 lines of code (vs NProgress v0.2.0 is 470 lines .js + 70 lines .css)
import { useRouter } from 'next/router';
import { useEffect } from 'react';
import { useProgressBar } from './useProgressBar';
// https://github.com/twbs/bootstrap/blob/v5.3.0-alpha1/scss/_variables.scss#L1529
const transitionSpeed = 600;
// https://gist.github.com/tkrotoff/db8a8106cc93ae797ea968d78ea28047
// https://stackoverflow.com/q/60755316
@tkrotoff
tkrotoff / #calculator.ts
Last active April 9, 2024 14:45
Calculator function using shunting yard algorithm and reverse Polish notation (RPN)
// https://gist.github.com/tkrotoff/b0b1d39da340f5fc6c5e2a79a8b6cec0
// WTF!
// parseFloat('-0') => -0 vs parseFloat(-0) => 0
// -0 === 0 => true vs Object.is(-0, 0) => false
const minus0Hack = (value: number) => (Object.is(value, -0) ? '-0' : value);
export const operators: {
[operator: string]:
| {
@tkrotoff
tkrotoff / #wait.ts
Last active June 18, 2023 08:47
Cancelable await wait()
// https://gist.github.com/tkrotoff/c6dd1cabf5570906724097c6e3f65a12
// https://stackoverflow.com/a/67911932
export function wait(ms: number, options: { signal?: AbortSignal } = {}) {
const { signal } = options;
return new Promise<void>((resolve, reject) => {
// FIXME Not supported by Jest 29.3.1 + Node.js 19.3.0
//signal?.throwIfAborted();
if (signal?.aborted) reject(signal.reason);