当前位置:网站首页>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
边栏推荐
- 微机原理与接口技术知识点整理复习–纯手打
- Jenkins+webhooks-多分支参数化构建-
- Simple two ball loading
- MySQL gap lock
- 面试题目总结(1) https中间人攻击,ConcurrentHashMap的原理 ,serialVersionUID常量,redis单线程,
- 【机器学习】VAE变分自编码器学习笔记
- 【牛客刷题-SQL大厂面试真题】NO2.用户增长场景(某度信息流)
- Listen in the network
- 【大型电商项目开发】性能压测-压力测试基本概念&JMeter-38
- Yarn restart applications record recovery
猜你喜欢

Detailed explanation of OSPF LSA of routing Foundation

研发效能度量框架解读

Feign & Eureka & Zuul & Hystrix 流程

minimum spanning tree

mysql统计账单信息(下):数据导入及查询

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

孔松(信通院)-数字化时代云安全能力建设及趋势

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

启动solr报错The stack size specified is too small,Specify at least 328k

MySQL 66 questions, 20000 words + 50 pictures in detail! Necessary for review
随机推荐
leetcode 322. Coin change (medium)
Jenkins+webhooks-多分支参数化构建-
Introduction to topological sorting
股票开户要认识谁?实际上网上开户安全么?
Analysis report on the development pattern of China's smart emergency industry and the 14th five year plan Ⓠ 2022 ~ 2028
JS discolored Lego building blocks
In the next stage of digital transformation, digital twin manufacturer Youyi technology announced that it had completed a financing of more than 300 million yuan
用命令行 给 apk 签名
arthas使用
Beidou communication module Beidou GPS module Beidou communication terminal DTU
单工,半双工,全双工区别以及TDD和FDD区别
1553B environment construction
Global and Chinese polypropylene industry prospect analysis and market demand forecast report Ⓝ 2022 ~ 2027
C language learning
1553B环境搭建
Declare an abstract class vehicle, which contains the private variable numofwheel and the public functions vehicle (int), horn (), setnumofwheel (int) and getnumofwheel (). Subclass mot
MySQL statistical bill information (Part 2): data import and query
Router. use() requires a middleware function but got a Object
Report on the "14th five year plan" and scale prospect prediction of China's laser processing equipment manufacturing industry Ⓢ 2022 ~ 2028
Investment analysis and prospect prediction report of global and Chinese dimethyl sulfoxide industry Ⓦ 2022 ~ 2028