当前位置:网站首页>Summary of 20 practical typescript single line codes
Summary of 20 practical typescript single line codes
2022-07-01 13:31:00 【Xianling Pavilion】
In today's article , I will share with you 20 Helpful TypeScript Single line code , These single line codes can quickly help us improve our development efficiency , I hope it works for you .
Let's start now .
01、 Wait for a specific amount of time ( In Milliseconds )
const wait = (ms: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, ms));
await wait(1000); // waiting 1 second
02、 Check whether the date is a working day
const isWeekday = (d: Date): boolean => d.getDay() % 6 !== ;
isWeekday(new Date(2022, 2, 21)); // -> true
isWeekday(new Date(2021, 2, 20)); // -> false
03、 Reverse string
const reverse = (s: string): string => s.split('').reverse().join('');
reverse('elon musk'); // -> 'ksum nole'
04、 Check whether a number is even .
const isEven = (n: number): boolean => n % 2 === ;
isEven(2); // -> true
isEven(3); // -> false
05、 Uppercase string
const capitalize = (s: string): string => s.charAt().toUpperCase() + s.slice(1);
capitalize('lorem ipsum'); // -> Lorem ipsum
06、 Check if the array is empty
const isArrayEmpty = (arr: unknown[]): boolean => Array.isArray(arr) && !arr.length;
isArrayEmpty([]); // -> true
isArrayEmpty([1, 2, 3]); // -> false
07、 Check the object / Whether the array is empty
const isObjectEmpty = (obj: unknown): boolean => obj && Object.keys(obj).length === ;
isObjectEmpty({
}); // -> true
isObjectEmpty({
foo: 'bar' }); // -> false
08、 Randomly generate integers
Generate a random integer based on two parameters .
const randomInteger = (min: number, max: number): number => Math.floor(Math.random() * (max - min + 1)) + min;
randomInteger(1, 10); // -> 7
09、 Generate random Boolean values
const randomBoolean = (): boolean => Math.random() >= 0.5;
randomBoolean(); // -> true
10、 Toggle Boolean
Toggle Boolean , Turn false into true , Turn true into false .
const toggleBoolean = (val: boolean): boolean => (val = !val);
toggleBoolean(true); // -> false
11、 transformation
Convert a string to a string with “-” Hyphenation string of .
const slugify = (str: string): string => str.toLowerCase().replace(/\s+/g, '-').replace(/[^\w-]+/g, '');
slugify('Hello World'); // -> hello-world
12、 Generate combinations with arrays
Randomly generate a set of arrays of any type .
const shuffleArray = <T>(arr: T[]): T[] => arr.sort(() => Math.random() - 0.5);
shuffleArray(<number[]>[1, 2, 3, 4, 5]); // -> [ 4, 5, 2, 1, 3 ]
13、 Convert ligature string to Luofeng string
const snakeToCamel = (s: string): string => s.toLowerCase().replace(/(_\w)/g, (w) => w.toUpperCase().substring(1));
snakeToCamel('foo_bar'); // -> fooBar
14、 Random integers
Generate a random integer according to the current time .
const randomInteger = (): number => new Date().getTime();
randomInteger(); // -> 1646617367345
15、 Random number string
Generate a random number string according to the current time .
const randomNumberString = (): string => new Date().getTime() + Math.random().toString(36).slice(2);
randomNumberString(); // -> 1646617484381wml196a8iso
16、 Convert numbers to characters / Letter
const numberToLetter = (value: number): string => String.fromCharCode(94 + value);
numberToLetter(4); // -> b
17、 Generate random hex colors
const randomHexColor = (): string => `#${
Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;
randomHexColor(); // -> #dc7c40
18、 Delete the trailing slash of the string
const removeTrailingSlash = (value: string): string => value && value.charAt(value.length - 1) === '/' ? value.slice(, -1) : value;
removeTrailingSlash('foo-bar/'); // -> foo-bar
19、 Get the random items of the array
const randomItem = <T>(arr: T[]): T => arr[(Math.random() * arr.length) | ];
randomItem(<number[]>[1, 2, 3, 4, 5]); // -> 4
20、 Convert uppercase strings to lowercase
const decapitalize = (str: string): string => `${
str.charAt(0).toLowerCase()}${
str.slice(1)}`;
decapitalize('Hello world'); // -> hello world
The source code attachment has been packaged and uploaded to Baidu cloud , You can download it yourself ~
link : https://pan.baidu.com/s/14G-bpVthImHD4eosZUNSFA?pwd=yu27
Extraction code : yu27
Baidu cloud link is unstable , It may fail at any time , Let's keep it tight .
If Baidu cloud link fails , Please leave me a message , When I see it, I will update it in time ~
Open source address
Code cloud address :
http://github.crmeb.net/u/defu
Github Address :
http://github.crmeb.net/u/defu
source | https://blog.bitsrc.io/another-10-quick-typescript-one-liners-9f41713c158a
边栏推荐
- French Data Protection Agency: using Google Analytics or violating gdpr
- 1553B environment construction
- MySQL Replication中的并行复制示例详解
- Social distance (cow infection)
- 微机原理与接口技术知识点整理复习–纯手打
- 机器学习—性能度量
- Colorful five pointed star SVG dynamic web page background JS special effect
- Apache-Atlas-2.2.0 独立编译部署
- Reasons for MySQL reporting 1040too many connections and Solutions
- Asp. NETCORE uses dynamic to simplify database access
猜你喜欢

学历、长相、家境普通的人,未来的发展方向是什么?00后的职业规划都已经整得明明白白......

Function test process in software testing

minimum spanning tree

Feign & Eureka & Zuul & Hystrix 流程

Judea pearl, Turing prize winner: 19 causal inference papers worth reading recently

8 popular recommended style layout

VM virtual machine configuration dynamic IP and static IP access

Fiori 应用通过 Adaptation Project 的增强方式分享

硬件开发笔记(九): 硬件开发基本流程,制作一个USB转RS232的模块(八):创建asm1117-3.3V封装库并关联原理图元器件

Computer network interview knowledge points
随机推荐
1.8新特性-List
JS变色的乐高积木
20个实用的 TypeScript 单行代码汇总
研发效能度量框架解读
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
Camp division of common PLC programming software
Have you ever encountered the problem that flynk monitors the PostgreSQL database and checkpoints cannot be used
内容审计技术
JS discolored Lego building blocks
声明一个抽象类Vehicle,它包含私有变量numOfWheels和公共函数Vehicle(int)、Horn()、setNumOfWheels(int)和getNumOfWheels()。子类Mot
Investment analysis and prospect prediction report of global and Chinese p-nitrotoluene industry Ⓙ 2022 ~ 2027
学历、长相、家境普通的人,未来的发展方向是什么?00后的职业规划都已经整得明明白白......
ArrayList扩容机制以及线程安全性
Shangtang technology crash: a script written at the time of IPO
机器学习—性能度量
Introduction to reverse debugging PE structure input table output table 05/07
Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
Research Report on China's software outsourcing industry investment strategy and the 14th five year plan Ⓡ 2022 ~ 2028
基于mysql乐观锁实现秒杀的示例代码
Global and Chinese styrene acrylic lotion polymer development trend and prospect scale prediction report Ⓒ 2022 ~ 2028