Code Snippets

That's a collection of code snippets you can copy and paste

Create Objects from Arrays

This function lets you create an object made up of an array of objects with an 'id' key and any number of additional properties.

js
1const indexOn = (array, key) =>
2 array.reduce((object, value) => {
3 const { [key]: id, ...data } = value;
4 object[id] = data;
5
6 return object;
7 }, {});
8
9// Usage
10indexOn(
11 [
12 { id: 1, name: 'John', age: 30 },
13 { id: 2, name: 'Mary', age: 25 },
14 ],
15 'id',
16);
17
18// [ { id: 1, name: 'John', age: 30 }, { id: 2, name: 'Mary', age: 25 } ]

Create an Interval Hook

To create an interval hook, pass in a function to be called every interval with the args passed in the hook.

jsx
1import { useRef, useEffect, useState } from 'react';
2
3const useInterval = (callback, delay) => {
4 const savedCallback = useRef();
5
6 useEffect(() => {
7 savedCallback.current = callback;
8 }, [callback]);
9
10 useEffect(() => {
11 const tick = () => {
12 savedCallback.current();
13 };
14
15 if (delay !== null) {
16 let id = setInterval(tick, delay);
17 return () => clearInterval(id);
18 }
19 }, [delay]);
20};
21
22// Usage
23const Timer = () => {
24 const [seconds, setSeconds] = useState(0);
25
26 useInterval(() => {
27 setSeconds(seconds + 1);
28 }, 1000);
29
30 return <div>Seconds: {seconds}</div>;
31};

Convert a Tuple to a Union Type

TypeScript lets you create a union type from a tuple type. That's useful when you want to make a type that's a union of multiple types.

ts
1type UnionFromTuple<Tuple extends readonly (string | number | boolean)[]> =
2 Tuple[number];
3
4const animals = ['🐶', '🙀', '🐮'] as const;
5
6type Animal = UnionFromTuple<typeof animals>;
7
8// type Animal = '🐶' | '🙀' | '🐮';

Generate a Range of Numbers

This function returns an array of all numbers between the start and end numbers.

js
1const range = (options) => {
2 const { start = 0, end, step = 1 } = options;
3
4 if (!end || end <= start) {
5 return [];
6 }
7
8 return Array.from(
9 { length: Math.ceil((end - start) / step) },
10 (_, i) => i + step + start,
11 );
12};
13
14// Usage
15const r1 = range({ end: 10 });
16// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
17const r2 = range({ start: 10, end: 20 });
18// [ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 ]
19const r3 = range({ start: 10, end: 20, step: 2 });
20// [ 12, 13, 14, 15, 16 ]

Run Promises in Parallel

To run multiple promises in series, pass an array of promises to Promise.all(). The first one to resolve will be passed to the callback.

js
1async function updateUserInfo() {
2 await Promise.all([
3 updateUserName({ id: 1, name: 'Clown 🤡' }),
4 sendUpdateNotification({ id: 1 }),
5 cleanupOldLogs({ id: 1, cleanAll: true }),
6 ]);
7}