报纸打字项目

JS|TS By Example
JS | TS示例
您的TypeScript项目可能需要的十大实用工具(Top 10 Utilities you may need for your TypeScript Projects)
You work on multiple projects. Most of the time you repeat your self while writing common util functions. Here are some of the most useful utilities that you can use for your TypeScript or JavaScript
您从事多个项目。 大多数情况下,您在编写通用util函数时会重复自我。 以下是一些可用于TypeScript或JavaScript的最有用的实用程序
1. compact: Compact is normally used to remove the falsy value from an Array. There are multiple variations of it.
1. compact:紧凑通常用于从数组中删除伪造的值。 它有多种变体。
Simple Variant: filter out falsy values (false
, null
, 0
, ""
, undefined
, and NaN
).
简单变体:过滤虚假值( false
, null
, 0
, ""
, undefined
和NaN
)。
// Code:const compact = (arr = []) => arr.filter(Boolean);// How to use itcompact([0, 1, false, 2, "", 3, "a", Number("e") * 23, NaN, "s", 34]); // [ 1, 2, 3, 'a', 's', 34 ]
Functional and Advanced Variation: You can also take a function as a parameter to define the behavior of the filter.
功能和高级变体:您也可以将函数用作参数来定义过滤器的行为。
// Code:
type Predicate<T> = (val: T) => boolean;const compact = <T = any>(fn: Predicate<T>, arr: T[] = []) => arr.filter(fn);
const removeFalsy = curry(compact, 2)(Boolean);
const removeNull = curry(compact, 2)((v: any) => v !== null);// How to use itremoveFalsy([0, false, "", 3, "a", Number("e") * 23, NaN, null])
// [ 3, 'a']removeNull([0, false, "", 3, "a", Number("e") * 23, NaN, null]);
// [ 0, false, '', 3, 'a', NaN, NaN, 's' ]
If you noticed, I am using function curry to make compact more functional, and reusable. We will learn curry later in this tutorial.
如果您注意到,我正在使用函数库里使紧凑的函数功能更强,并且可重用。 我们将在本教程的后面部分学习咖喱。
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/compact
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/compact
2. contains The other useful function, I used in most of the projects. After ES 2015, JavaScript does have includes. However, most of the time you end-up error like toLowerCase of undefined is not function. You have to handle boundary cases.
2.包含其他有用的功能,我在大多数项目中都使用过。 在ES 2015之后,JavaScript确实包含了。 但是,大多数情况下,最终错误(例如toLowerCase的undefined)不会起作用。 您必须处理边界情况。
// Code:
const contains = (s1: string, s2: string = "") =>
s1.toLowerCase().indexOf(s2.toLowerCase()) !== -1// How to use itcontains("Text1", "Ext"); // truecontains("Text1", "et"); // false
Above util is case insensitive in nature. You can update according to your need.
上面的util本质上不区分大小写。 您可以根据需要进行更新。
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/contains
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/contains
3. curry: If you love functional programming. You can’t skip the curry method in your toolbox. curry is one of the most basic needs of functional programming. However, Defining curry function is TypeScript could be a challenge. Bellow example I defined based on my knowledge. You can find a better variant of it online.
3. curry:如果您喜欢函数式编程。 您不能在工具箱中跳过curry方法。 咖喱是函数式编程的最基本需求之一。 但是,定义Curry函数是TypeScript可能是一个挑战。 我根据自己的知识定义了贝娄示例。 您可以在线找到它的更好的变体。
Concept of curry: https://en.wikipedia.org/wiki/Currying
咖喱的概念: https : //en.wikipedia.org/wiki/咖喱
// Code:
const curry = (fn: Function, arity = fn.length, ...args: any[]): any => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);// How to use itconst removeFalsy = curry(compact, 2)(Boolean);
const removeNull = curry(compact, 2)((v: any) => v !== null);
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/curry
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/curry

4. delay: delay is very useful in testing some asynchronous methods. This helps to put some virtual delay to mimic the network call or any async side-effect.
4.延迟:延迟在测试某些异步方法中非常有用。 这有助于放置一些虚拟延迟来模仿网络呼叫或任何异步副作用。
Simple Variant:
简单变体:
// Code
const delay = (fn: Function, wait: number, ...args: any[]) => setTimeout(fn, wait, ...args);// How to use itdelay(
function (text) {
console.log(text);
},
1000,
"later"
);
// Logs 'later' after one second.
Promise Variant: If you needed you can create a Promise variant of it. Just wrap delay in promise.
Promise变体:如果需要,可以为其创建Promise变体。 只要在承诺中包上延迟。
// Code
const delayedPromise = (wait: number = 300, ...args: any[]) =>
new Promise((resolve) => {
delay(resolve, wait, ...args);
});// How to use it(async function () {
await delayedPromise();
console.log("Print after delay");
})();
// Print after delay
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/delay
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/delay
5. unique: This is used to get the unique values in a given array. This could also have multiple variants. The simplest one uses Set to push values and collect unique value.
5. unique:用于获取给定数组中的唯一值。 这也可以有多个变体。 最简单的方法是使用Set推送值并收集唯一值。
// Code
const unique = (arr: any[]) => [...new Set(arr)];// How to use itunique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
You can also pass a function to define the uniqueness of the value.
您还可以传递一个函数来定义值的唯一性。
// Code
const uniqueBy = (fn: Predicate, arr: any[]) =>
arr.reduce((acc, v) => {
if (!acc.some((x: any) => fn(v, x))) acc.push(v);
return acc;
}, []);// How to use ituniqueBy(
(a: any, b: any) => a.id == b.id,
[
{ id: 0, value: "a" },
{ id: 1, value: "b" },
{ id: 2, value: "c" },
{ id: 1, value: "d" },
{ id: 0, value: "e" },
],
); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/unique
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/unique
6. sum: Sum is one of the simplest but useful method you may want in your util library. You can use Array.reduce to sum the value.
6. sum: sum是您可能希望在util库中使用的最简单但有用的方法之一。 您可以使用Array.reduce对值求和。
// Code
const sum = (...arr: number[]) => [...arr].reduce((acc, val) => acc + val, 0);// How to use it
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
You can also pass a function as a parameter to extract the value to sum.
您还可以将函数作为参数传递,以提取要求和的值。
// Code
const sumBy = <T = any>(arr: T[], fn: string | ((a: T) => number)) => {
return arr
.map(typeof fn === "function" ? fn : (val: any) => val[fn])
.reduce((acc, val) => acc + val, 0);
};// How to use it
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], (o) => o.n); // 20
sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], "n"); // 20
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/sum
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/sum

7. sortBy: Sorting an array can be easily done using Array.sort. But saying so, There are still many edge cases you may want to handle in your util library. Here is some variation of my sortBy method.
7. sortBy:使用Array.sort可以很容易地对数组进行排序。 但要这样说,在util库中仍然可能需要处理许多极端情况。 这是我的sortBy方法的一些变体。
Code:
码:
type SortByFunc<T> = (s1: T, s2: T) => number;
enum SortByOrder {
ASC = 1,
DESC = -1,
}
const sortBy = <T = any>(
arr: T[],
$fn: SortByFunc<T> = (s1: any, s2: any) =>
order * String(s1).localeCompare(String(s2)),
order: SortByOrder = SortByOrder.ASC
) => {
let fn = $fn;
return [...arr].sort(fn);
};
How to use it:
如何使用它:
sortBy([1, 2, 4, 3, 4, -1]); // [-1, 1, 2, 3, 4, 4]
sortBy(["Test", "test"]); // ["Test", "test"]// Descending
sortBy([1, 2, 4, 3, 4, -1], undefined, -1); // [4, 4, 3, 2, 1, -1]sortBy([{ name: "02" }, { name: "01" }], (s1: any, s2: any) =>
s1.name.localeCompare(s2.name)
); //[{ name: "01" }, { name: "02" }]// Descending
sortBy(
[{ name: "02" }, { name: "01" }],
(s1: any, s2: any) => -1 * s1.name.localeCompare(s2.name)
); //[{ name: "02" }, { name: "01" }]
You also may want to sortBy key(passing the key name of the object to sort).
您可能还想按键排序(传递要排序的对象的键名称)。
// sortByKey
enum SortByOrder {
ASC = 1,
DESC = -1,
}
const sortByKey = <T = any>(
arr: T[],
key: string,
order: SortByOrder = SortByOrder.ASC
) => {
return [...arr].sort(
(s1: any, s2: any) => order * String(s1[key]).localeCompare(String(s2[key]))
);
};
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/sortBy
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/sortBy
8. randomInt: JavaScript is awesome and the same time is has a weird side of it. Generating a random integer in a given range could be one of the use cases for you.
8. randomInt: JavaScript非常棒,同时又有一个怪异的一面。 在给定范围内生成随机整数可能是您的用例之一。
// Code
const randomInt = (min = 0, max = 100) =>
Math.floor(Math.random() * (max - min + 1)) + min;// How to use it
console.log(randomInt(0, 5)); // 2
console.log(randomInt()); // 2
By default, It will generate Int between 0–100.
默认情况下,它将生成介于0到100之间的Int 。
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/randomInt
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/randomInt
9. isEmpty: JavaScript has so many types of Null/Falsy values. finding a nullify value could be one of the frustrating things in JavaScript. So having a method like isEmpty will make your util more useful.
9. isEmpty: JavaScript有很多类型的Null / Falsy值。 查找无效值可能是JavaScript中令人沮丧的事情之一。 因此,拥有isEmpty之类的方法将使您的工具更有用。
// Code
const isEmpty = (val: any) => val == null || !(Object.keys(val) || val).length;// How to use it
isEmpty([]); // true
isEmpty({}); // true
isEmpty(""); // true
isEmpty([1, 2]); // false
isEmpty({ a: 1, b: 2 }); // false
isEmpty("text"); // false
isEmpty(123); // true - type is not considered a collection
isEmpty(true); // true - type is not considered a collection
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/isEmpty
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/isEmpty
10. orderBy: Last but not least, orderBy. This is one of the most used methods in my library. Since now a day, the Browser can handle more complex computing. A lot of the logic has moved to the front-end. I use this method so often in my code.
10. orderBy:最后但并非最不重要的,orderBy。 这是我的库中最常用的方法之一。 从今天开始,浏览器可以处理更复杂的计算。 许多逻辑已经转移到前端。 我在代码中经常使用此方法。
// Code
const orderBy = <T = AnyObject>(
arr: T[],
props: (keyof T)[],
orders?: ("asc" | "desc")[]
) =>
[...arr].sort((a, b) =>
props.reduce((acc, prop, i) => {
if (acc === 0) {
const [p1, p2] =
orders && orders[i] === "desc"
? [b[prop], a[prop]]
: [a[prop], b[prop]];
acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0;
}
return acc;
}, 0)
);// How to use it
const users = [
{ name: "fred", age: 48 },
{ name: "barney", age: 36 },
{ name: "fred", age: 40 },
];
orderBy(users, ["name", "age"], ["asc", "desc"]); // [{name: 'barney', age: 36}, {name: 'fred', age: 48}, {name: 'fred', age: 40}]
orderBy(users, ["name", "age"]); // [{name: 'barney', age: 36}, {name: 'fred', age: 40}, {name: 'fred', age: 48}]
To learn more: https://decipher.dev/30-seconds-of-typescript/docs/orderBy
要了解更多信息: https : //decipher.dev/30-seconds-of-typescript/docs/orderBy
尊敬的提到: (Honorable mentioned:)
groupBy: https://decipher.dev/30-seconds-of-typescript/docs/groupByformatDate: https://decipher.dev/30-seconds-of-typescript/docs/formatDatearrayToCSV: https://decipher.dev/30-seconds-of-typescript/docs/arrayToCSVpluralize: https://decipher.dev/30-seconds-of-typescript/docs/pluralize
Note: If you like, You can download extension 30-seconds-of-typescript. This will give you the code snippets. You can also consume as an npm module and ES Import.
注意:如果愿意,您可以下载扩展名30秒的打字稿。 这将为您提供代码段。 您还可以将其用作npm模块和ES Import 。
// Import
const { mask } = require("@deepakvishwakarma/ts-util");// ES Importimport * as util from "https://cdn.jsdelivr.net/gh/deepakshrma/30-seconds-of-typescript/util.js";
To learn more visit: https://decipher.dev/30-seconds-of-typescript/docs/
要了解更多信息,请访问: https : //decipher.dev/30-seconds-of-typescript/docs/
翻译自: https://medium.com/@deepak_v/top-10-utilities-you-may-need-for-your-typescript-projects-6131d39fe618
报纸打字项目