@abhijithvijayan/ts-utils 中文文档教程

发布于 3 年前 浏览 30 项目主页 更新于 2 年前

@abhijithvijayan/ts-utils

JavaScript 实用函数集合

????‍♂️ Made by @abhijithvijayan

捐: 贝宝Patreon

给我买杯咖啡


❤️呢? ⭐️ 在 GitHubTweet 关于它。

Table of Contents

Installation

确保安装了 Node.js 10 或更高版本。 然后运行以下命令:

# via npm
npm install @abhijithvijayan/ts-utils

# or yarn
yarn add @abhijithvijayan/ts-utils

Usage

import {isNull, get} from '@abhijithvijayan/ts-utils';

API

  • isEmail(value):执行RFC2822 验证 发送电子邮件

  • isEmail("something@something.com"); // true

  • isEmail("foo...bar-5@qux.com" ); // false

  • isNull(value): 如果值为 null,则返回 true, < code>false 否则

  • isUn​​defined(value):如果值为 undefined,则返回 true,否则返回 false

  • isNullOrUndefined(value):如果值为 nullundefined,则返回 truefalse否则

  • isString(value):如果值为 string,则返回 true,否则返回 false

  • isNumber(value):如果值为 number,则返回 true,否则

  • 返回 false isFunction(value):返回 true 如果值为function,false otherwise

  • isEmpty(value):如果值为空对象,则返回true code>,collection,具有no enumerable properties 或者是不被视为collection

    • 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
  • size(value)

    • size([1, 2, 3, 4, 5]); // 5
    • size("size"); // 4
    • size(new Set([1, 2, 3])); // 3
    • size({ one: 1, two: 2, three: 3 }); // 3
  • 大小

    • splitArrayIntoChunks([0, 1, 2, 3, 4], 2); // [[0, 1], [2, 3], [4]]
    • splitArrayIntoChunks([0, 1, 2, 3, 4], 4); // [[0, 1, 2, 3], [4]]
  • > 的任何类型> ):删除string中的所有空格

    • removeWhitespaces("-- hello - world --"); // "--hello-world--"
  • capitalize(value, lowerRest):将string的第一个字母大写

    • lowerRest, if true, lower-cases the rest of the string, Default: false
    • capitalize("fooBar"); // 'FooBar'
    • capitalize("fooBar", true); // 'Foobar'
  • toCamelCase(value):将字符串转换为

    • toCamelCase("sometextfield_name"); // 'someTextFieldName'
    • toCamelCase("Some label that needs to be camelized"); // 'someLabelThatNeedsToBeCamelized'
    • toCamelCase("some-js-property"); // 'someJsProperty'
    • toCamelCase("some-mixedstring with spacesunderscores-and-hyphens"); // 'someMixedStringWithSpacesUnderscoresAndHyphens'
  • 驼峰式randomString():生成随机string

  • randomNumberInRange(min, max):返回一个介于 min(含)和 max(不含)之间的随机数

    • randomNumberInRange(10, 15); // 12.257101242652775
  • randomIntegerInRange(min, max: Returns a random integer between min (inclusive) and max (inclusive)

    • randomIntegerInRange(10, 20); // 16
  • round(num, decimals): 将数字四舍五入到指定数量的数字

    • round(1.005, 2); // 1.01
  • mask(value, num, maskWith): 替换所有,但最后一个num of characters with the specified mask character

    • If num is negative, the unmasked characters will be at the start of the string. Default: 4
    • maskWith changes default character for the mask. Default: *
    • mask(1234567890); // '7890'
    • mask(1234567890, 3); // '*890'
    • mask(1234567890, -4, "$"); // '$$$$567890'
  • fillArray(prop, value):用指定的值初始化并填充一个数组,返回一个array

    • prop: if number is passed, it will be used as the array size
    • prop: can be an object as well
      • length: array size
      • value: value to fill
      • fillIndex: if true, the array will be filled with index value (overrides value field)
    • fillArray(5, 2); // [2, 2, 2, 2, 2]
    • fillArray(3, {}); // [{}, {}, {}]
    • fillArray(1, null); // [null]
    • fillArray({length: 2, value: 'test'}); // ['test', 'test']
    • fillArray({length: 5, fillIndex: true}); // [0, 1, 2, 3, 4]
  • unique(arr)< /code>: 返回数组中的所有唯一值

    • unique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
  • take(arr): 返回从头开始取 n 个元素的数组

    • take([1, 2, 3], 5); // [1, 2, 3]
    • take([1, 2, 3], 0); // []
  • last(arr): 返回最后一个元素一个数组

    • last([1, 2, 3]); // 3
    • last([]); // undefined
    • last([null]); // null
    • last(undefined); // undefined
  • flatten(arr, depth):将一个数组展平到指定的深度,返回 array

    • depth, if passed, array will be flattened to the specified depth, else array will be flattened completely
    • flatten([1, [2, [3, [4, 5], 6], 7], 8]); // [1, 2, 3, 4, 5, 6, 7, 8]
    • flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
  • pipe(...fns):执行 left-向右函数组合(同步)

   const add5 = (x) => x + 5;
   const multiply = (x, y) => x * y;
   const multiplyAndAdd5 = pipe(multiply, add5);
   multiplyAndAdd5(5, 2); // 15
  • get(from, selector, defaultValue): Retrieve a property indicated by the given selector from an object
   const obj = { selector: { to: { val: "val to select" } }, target: [1, 2, { a: "test" }], };

   get(obj, "selector.to.val"); //"val to select"
   get(obj, "selector.to1.val", null); // null
   get(obj, "target.2.a"); // "test"
   get(obj, "selector.to1.val"); // undefined
   get(obj, "selector[to][val]"); // "val to select"
   get(obj, "target.2.[a]"); // "test"
   get(null, "something"); // undefined
   get(undefined, "something", 123); // 123
  • debounce(fn, wait): Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked
    • wait: Time in milliseconds Default: 100
   window.addEventListener("resize", debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
   }, 250)); // Will log the window dimensions at most every 250ms
  • throttle(fn, wait): Creates a throttled function that only invokes fn at most once per wait milliseconds
    • wait: Time in milliseconds Default: 100
  • sleep(ms): Delays the execution of an asynchronous function
    • ms: Time in milliseconds Default: 100
  async function sleepyWork() {
   console.log("I'm going to sleep for 1 second.");
   await sleep(1000);
   console.log("I woke up after 1 second.");
  }
  • objectToQueryParams(queryParams):返回从给定对象的键值对生成的查询字符串

    • Note:
      • undefined and NaN values(nested) will be skipped automatically
      • value will be empty string for functions and null
      • nested arrays will be flattened
    • objectToQueryParams(undefined); // ""
    • objectToQueryParams(null); // ""
    • objectToQueryParams({}); // ""
    • objectToQueryParams({ page: "1", limit: "10", key: undefined }); // 'page=1&limit=10'
    • With a complex object that has nested values
      objectToQueryParams({
          foo: 'hello world', // resolves to [ "foo", "hello world" ]
          bar: {
              blah: 123, // resolves to [ "bar[blah]", "123" ]
              list: [1, 2, 3], // resolves to [ "bar[list][]", "1" ], [ "bar[list][]", "2" ], [ "bar[list][]", "3" ]
              'nested array': [[4,5],[6,7]] // resolves to [ "bar[nested array][][]", "4" ], [ "bar[nested array][][]", "5" ], [ "bar[nested array][][]", "6" ], [ "bar[nested array][][]", "7" ]
          },
          page: 1, // resolves to [ "page", "1" ]
          limit: undefined, // ignored
          check: false, // resolves to [ "check", "false" ]
          max: NaN, // ignored
          prop: null, // resolves to [ "prop", "" ]
          ' key value': 'with spaces' // resolves to [ "key value", "with spaces" ]
      }); // foo=hello%20world&bar[blah]=123&bar[list][]=1&bar[list][]=2&bar[list][]=3&bar[nested%20array][][]=4&bar[nested%20array][][]=5&bar[nested%20array][][]=6&bar[nested%20array][][]=7&page=1&check=false&prop=&key%20value=with%20spaces
    
      let params = new URLSearchParams(window.location.search);
      for (const param of p) {
          console.log(param); // [ "foo", "hello world" ], [ "bar[blah]", "123" ], ...
      }
    
  • isBrowser():确定当前是否运行时环境是浏览器

  • isIP(str): 测试输入是否是 IP 地址 ess

    • Returns
    • 0 for invalid strings, // eg: 1.1.1.01, 1::2::3
    • 4 for IP version 4 addresses, // eg: 127.0.0.1, 192.168.1.1
    • 6 for IP version 6 addresses, // eg: 1::, ff02::1, 1:2:3:4::6:7:8

Issues

想要做出贡献? 寻找 首期不错 标签。

Bugs

请在此处提交有关错误、文档缺失或意外行为的问题。

查看 Bug

Linting & TypeScript Config

Credits

一些实用程序继承自 https://www.30secondsofcode.org/js/p/1

License

MIT © Abhijith维杰安

@abhijithvijayan/ts-utils

Collection of JavaScript utility functions

????‍♂️ Made by @abhijithvijayan

Donate: PayPal, Patreon

Buy Me a Coffee


❤️ it? ⭐️ it on GitHub or Tweet about it.

Table of Contents

Installation

Ensure you have Node.js 10 or later installed. Then run the following:

# via npm
npm install @abhijithvijayan/ts-utils

# or yarn
yarn add @abhijithvijayan/ts-utils

Usage

import {isNull, get} from '@abhijithvijayan/ts-utils';

API

  • isEmail(value): Performs RFC2822 Validation to email

  • isEmail("something@something.com"); // true

  • isEmail("foo...bar-5@qux.com"); // false

  • isNull(value): Returns true if value is null, false otherwise

  • isUndefined(value): Returns true if value is undefined, false otherwise

  • isNullOrUndefined(value): Returns true if value is null or undefined, false otherwise

  • isString(value): Returns true if value is string, false otherwise

  • isNumber(value): Returns true if value is number, false otherwise

  • isFunction(value): Returns true if value is function, false otherwise

  • isEmpty(value): Returns true if the value is an empty object, collection, has no enumerable properties or is any type that is not considered a collection

    • 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
  • size(value): Gets the size of an array, object, set or string

    • size([1, 2, 3, 4, 5]); // 5
    • size("size"); // 4
    • size(new Set([1, 2, 3])); // 3
    • size({ one: 1, two: 2, three: 3 }); // 3
  • splitArrayIntoChunks(arr, size): Splits array into chunks of arrays, Returns array

    • splitArrayIntoChunks([0, 1, 2, 3, 4], 2); // [[0, 1], [2, 3], [4]]
    • splitArrayIntoChunks([0, 1, 2, 3, 4], 4); // [[0, 1, 2, 3], [4]]
  • removeWhitespaces(value): Remove all whitespaces from a string

    • removeWhitespaces("-- hello - world --"); // "--hello-world--"
  • capitalize(value, lowerRest): Capitalizes the first letter of a string

    • lowerRest, if true, lower-cases the rest of the string, Default: false
    • capitalize("fooBar"); // 'FooBar'
    • capitalize("fooBar", true); // 'Foobar'
  • toCamelCase(value): Converts a string to camelcase

    • toCamelCase("sometextfield_name"); // 'someTextFieldName'
    • toCamelCase("Some label that needs to be camelized"); // 'someLabelThatNeedsToBeCamelized'
    • toCamelCase("some-js-property"); // 'someJsProperty'
    • toCamelCase("some-mixedstring with spacesunderscores-and-hyphens"); // 'someMixedStringWithSpacesUnderscoresAndHyphens'
  • randomString(): Generates a random string

  • randomNumberInRange(min, max): Returns a random number between min (inclusive) and max (exclusive)

    • randomNumberInRange(10, 15); // 12.257101242652775
  • randomIntegerInRange(min, max: Returns a random integer between min (inclusive) and max (inclusive)

    • randomIntegerInRange(10, 20); // 16
  • round(num, decimals): Rounds a number to a specified amount of digits

    • round(1.005, 2); // 1.01
  • mask(value, num, maskWith): Replaces all, but the last num of characters with the specified mask character

    • If num is negative, the unmasked characters will be at the start of the string. Default: 4
    • maskWith changes default character for the mask. Default: *
    • mask(1234567890); // '7890'
    • mask(1234567890, 3); // '*890'
    • mask(1234567890, -4, "$"); // '$$$$567890'
  • fillArray(prop, value): Initializes and fills an array with the specified values, Returns an array

    • prop: if number is passed, it will be used as the array size
    • prop: can be an object as well
      • length: array size
      • value: value to fill
      • fillIndex: if true, the array will be filled with index value (overrides value field)
    • fillArray(5, 2); // [2, 2, 2, 2, 2]
    • fillArray(3, {}); // [{}, {}, {}]
    • fillArray(1, null); // [null]
    • fillArray({length: 2, value: 'test'}); // ['test', 'test']
    • fillArray({length: 5, fillIndex: true}); // [0, 1, 2, 3, 4]
  • unique(arr): Returns all unique values in an array

    • unique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
  • take(arr): Returns an array with n elements taken from the beginning

    • take([1, 2, 3], 5); // [1, 2, 3]
    • take([1, 2, 3], 0); // []
  • last(arr): Returns the last element in an array

    • last([1, 2, 3]); // 3
    • last([]); // undefined
    • last([null]); // null
    • last(undefined); // undefined
  • flatten(arr, depth): Flattens an array to specified depth, Returns array

    • depth, if passed, array will be flattened to the specified depth, else array will be flattened completely
    • flatten([1, [2, [3, [4, 5], 6], 7], 8]); // [1, 2, 3, 4, 5, 6, 7, 8]
    • flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
  • pipe(...fns): Performs left-to-right function composition(synchronous)

   const add5 = (x) => x + 5;
   const multiply = (x, y) => x * y;
   const multiplyAndAdd5 = pipe(multiply, add5);
   multiplyAndAdd5(5, 2); // 15
  • get(from, selector, defaultValue): Retrieve a property indicated by the given selector from an object
   const obj = { selector: { to: { val: "val to select" } }, target: [1, 2, { a: "test" }], };

   get(obj, "selector.to.val"); //"val to select"
   get(obj, "selector.to1.val", null); // null
   get(obj, "target.2.a"); // "test"
   get(obj, "selector.to1.val"); // undefined
   get(obj, "selector[to][val]"); // "val to select"
   get(obj, "target.2.[a]"); // "test"
   get(null, "something"); // undefined
   get(undefined, "something", 123); // 123
  • debounce(fn, wait): Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked
    • wait: Time in milliseconds Default: 100
   window.addEventListener("resize", debounce(() => {
    console.log(window.innerWidth);
    console.log(window.innerHeight);
   }, 250)); // Will log the window dimensions at most every 250ms
  • throttle(fn, wait): Creates a throttled function that only invokes fn at most once per wait milliseconds
    • wait: Time in milliseconds Default: 100
  • sleep(ms): Delays the execution of an asynchronous function
    • ms: Time in milliseconds Default: 100
  async function sleepyWork() {
   console.log("I'm going to sleep for 1 second.");
   await sleep(1000);
   console.log("I woke up after 1 second.");
  }
  • objectToQueryParams(queryParams): Returns a query string generated from the key-value pairs of the given object

    • Note:
      • undefined and NaN values(nested) will be skipped automatically
      • value will be empty string for functions and null
      • nested arrays will be flattened
    • objectToQueryParams(undefined); // ""
    • objectToQueryParams(null); // ""
    • objectToQueryParams({}); // ""
    • objectToQueryParams({ page: "1", limit: "10", key: undefined }); // 'page=1&limit=10'
    • With a complex object that has nested values
      objectToQueryParams({
          foo: 'hello world', // resolves to [ "foo", "hello world" ]
          bar: {
              blah: 123, // resolves to [ "bar[blah]", "123" ]
              list: [1, 2, 3], // resolves to [ "bar[list][]", "1" ], [ "bar[list][]", "2" ], [ "bar[list][]", "3" ]
              'nested array': [[4,5],[6,7]] // resolves to [ "bar[nested array][][]", "4" ], [ "bar[nested array][][]", "5" ], [ "bar[nested array][][]", "6" ], [ "bar[nested array][][]", "7" ]
          },
          page: 1, // resolves to [ "page", "1" ]
          limit: undefined, // ignored
          check: false, // resolves to [ "check", "false" ]
          max: NaN, // ignored
          prop: null, // resolves to [ "prop", "" ]
          ' key value': 'with spaces' // resolves to [ "key value", "with spaces" ]
      }); // foo=hello%20world&bar[blah]=123&bar[list][]=1&bar[list][]=2&bar[list][]=3&bar[nested%20array][][]=4&bar[nested%20array][][]=5&bar[nested%20array][][]=6&bar[nested%20array][][]=7&page=1&check=false&prop=&key%20value=with%20spaces
    
      let params = new URLSearchParams(window.location.search);
      for (const param of p) {
          console.log(param); // [ "foo", "hello world" ], [ "bar[blah]", "123" ], ...
      }
    
  • isBrowser(): Determines if the current runtime environment is a browser

  • isIP(str): Tests if input is an IP address

    • Returns
    • 0 for invalid strings, // eg: 1.1.1.01, 1::2::3
    • 4 for IP version 4 addresses, // eg: 127.0.0.1, 192.168.1.1
    • 6 for IP version 6 addresses, // eg: 1::, ff02::1, 1:2:3:4::6:7:8

Issues

Looking to contribute? Look for the Good First Issue label.

???? Bugs

Please file an issue here for bugs, missing documentation, or unexpected behavior.

See Bugs

Linting & TypeScript Config

Credits

Some utils are inherited from https://www.30secondsofcode.org/js/p/1

License

MIT © Abhijith Vijayan

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文