Preface:
Generally, less code usually means better code. Therefore, today, I will share with you 7 single-line codes of TypeScript, including high-level usages such as generics and assertions. I hope it will be helpful to you.
1. Visible at the bottom
Determines whether the bottom of the page is visible.
const bottomVisible = (): boolean => + >= ( || );
2. Block array
Array of blocks based on incoming size.
const chunkArray = <T>(arr: T[], size: number) => [...new Array(( / size))].map((_, i) => (i * size, (i + 1) * size), ); // [ [ 0, 1 ], [ 2, 3 ], [ 4 ] ] (chunkArray([0, 1, 2, 3, 4], 2)); // [ [ 0, 1, 2, 3, 4 ] ] (chunkArray([0, 1, 2, 3, 4], 100));
3、mask
Encrypted characters, you can choose the number of characters that are reserved at the end, or you can customize the encrypted characters.
const mask = (char: number | string, num = 0, mask = '*') => String(char).slice(-num).padStart(String(char).length, mask); (mask('123')); // 123 (mask('123456789', 4)); // *****6789 (mask('123456789', 3, '#')); // ######789
4、on / off
Add/remove event listeners for DOM elements or event delegate objects without the hassle of addingEventListener/removeEventListener.
const on = <T extends Window | Document | HTMLElement | EventTarget>( obj: T | null, ...args: Parameters<T['addEventListener']> | [string, Function | null, ...any] ): void => { obj?.addEventListener?.( ...(args as Parameters<HTMLElement['addEventListener']>), ); }; const off = <T extends Window | Document | HTMLElement | EventTarget>( obj: T | null, ...args: | Parameters<T['removeEventListener']> | [string, Function | null, ...any] ): void => { obj?.removeEventListener?.( ...(args as Parameters<HTMLElement['removeEventListener']>), ); };
5、getUUID
Generate UUIDs that comply with RFC4122 Version 4 using the encryption API available in the browser.
const getUUID = () => (String(1e7) + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => ( Number(c) ^ ((new Uint8Array(1))[0] & (15 >> (Number(c) / 4))) ).toString(16), ); (getUUID());
6、once
Execute the function once.
const once = <T extends (...args: any) => any>(fn: T) => ( (ran = false) => (): ReturnType<T> => ran ? fn : ((ran = !ran), (fn = fn())) )(); let n = 1; const incOnce = once(() => ++n); (incOnce()); // 2 (incOnce()); // 2 (incOnce()); // 2 ('n: ', n); // n: 2
7. Database
Has the input string into an integer.
const sdbm = (str: string) => str .split('') .reduce( (acc, cur) => (acc = (0) + (acc << 6) + (acc << 16) - acc), 0, ); (sdbm('Hello')); // -1421493998 (sdbm('Hello')); // -1421493998 (sdbm('World')); // -2242392430
This is the end of this article about sharing 7 practical TypeScript single-line code. For more related TypeScript single-line code content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!