当前位置:网站首页>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
边栏推荐
- 盲盒NFT数字藏品平台系统开发(搭建源码)
- What is the future development direction of people with ordinary education, appearance and family background? The career planning after 00 has been made clear
- Nexus builds NPM dependent private database
- Colorful five pointed star SVG dynamic web page background JS special effect
- 软件测试中功能测试流程
- The stack size specified is too small, specify at least 328k
- Flow management technology
- 1553B环境搭建
- 硬件开发笔记(九): 硬件开发基本流程,制作一个USB转RS232的模块(八):创建asm1117-3.3V封装库并关联原理图元器件
- MySQL statistical bill information (Part 2): data import and query
猜你喜欢
![Idea of [developing killer]](/img/74/f4a18afd2b86373996e4ca62b50f88.png)
Idea of [developing killer]

Cs5268 advantages replace ag9321mcq typec multi in one docking station scheme

Introduction to reverse debugging PE structure input table output table 05/07

Feign & Eureka & zuul & hystrix process

Colorful five pointed star SVG dynamic web page background JS special effect
基于mysql乐观锁实现秒杀的示例代码

终端识别技术和管理技术

Fiori applications are shared through the enhancement of adaptation project

波浪动画彩色五角星loader加载js特效

1553B environment construction
随机推荐
8 popular recommended style layout
北斗通信模块 北斗gps模块 北斗通信终端DTU
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
Professor Li Zexiang, Hong Kong University of science and technology: I'm wrong. Why is engineering consciousness more important than the best university?
新手准备多少钱可以玩期货?农产品可以吗?
受益互联网出海 汇量科技业绩重回高增长
软件测试中功能测试流程
运行游戏时出现0xc000007b错误的解决方法[通俗易懂]
Report on the 14th five year plan and future development trend of China's integrated circuit packaging industry Ⓓ 2022 ~ 2028
20个实用的 TypeScript 单行代码汇总
MySQL Replication中的并行复制示例详解
1553B environment construction
French Data Protection Agency: using Google Analytics or violating gdpr
Flutter SQLite使用
Analysis report on the development pattern of China's smart emergency industry and the 14th five year plan Ⓠ 2022 ~ 2028
Build a vc2010 development environment and create a tutorial of "realizing Tetris game in C language"
Leetcode第一题:两数之和(3种语言)
6. Wiper part
1. Sum of two numbers: given an integer array num and an integer target value, please find the two integers whose sum is the target value target in the array and return their array subscripts
Analysis report on production and marketing demand and investment forecast of global and Chinese diamond powder industry Ⓤ 2022 ~ 2027