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;56 return object;7 }, {});89// Usage10indexOn(11 [12 { id: 1, name: 'John', age: 30 },13 { id: 2, name: 'Mary', age: 25 },14 ],15 'id',16);1718// [ { 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';23const useInterval = (callback, delay) => {4 const savedCallback = useRef();56 useEffect(() => {7 savedCallback.current = callback;8 }, [callback]);910 useEffect(() => {11 const tick = () => {12 savedCallback.current();13 };1415 if (delay !== null) {16 let id = setInterval(tick, delay);17 return () => clearInterval(id);18 }19 }, [delay]);20};2122// Usage23const Timer = () => {24 const [seconds, setSeconds] = useState(0);2526 useInterval(() => {27 setSeconds(seconds + 1);28 }, 1000);2930 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];34const animals = ['🐶', '🙀', '🐮'] as const;56type Animal = UnionFromTuple<typeof animals>;78// 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;34 if (!end || end <= start) {5 return [];6 }78 return Array.from(9 { length: Math.ceil((end - start) / step) },10 (_, i) => i + step + start,11 );12};1314// Usage15const 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}