npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@icreate/ics-utils

v0.0.13-beta.11

Published

- [方法集合](#方法集合) - [引用](#引用) - [注意!后续方法使用说明忽略了前缀,使用时请自行添加](#注意后续方法使用说明忽略了前缀使用时请自行添加) - [boolean 返回boolean](#boolean-返回boolean) - [equals 两个值之间的深入比较,以确定它们是否相等](#equals-两个值之间的深入比较以确定它们是否相等) - [hasOverflow 判断元素是否超出内容区(是否应该出现滚动

Downloads

51

Readme

方法集合

引用

import {
    boolean,
    date,
    node,
    number,
    object,
    string,
    system
    } from '@icreate/ics-utils'
/**
 * 例子:使用boolean下的equals方法
 */
boolean.equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4]})

注意!后续方法使用说明忽略了前缀,使用时请自行添加

boolean 返回boolean

equals 两个值之间的深入比较,以确定它们是否相等
/**
 * 两个值之间的深入比较,以确定它们是否相等
 *
 * @param {Object} a
 * @param {Object} b
 * @returns {*}
 * @example
 */
 equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
hasOverflow 判断元素是否超出内容区(是否应该出现滚动条)
/**
 * It checks if the target element has overflow content
 * @param {Element} element - DOM element target
 * @returns {boolean} true if the target element has overflow content
 * @example
 * <div class="box flex" style="widht: 100px;">
 *  <div style="width: 200px;">
 * </div>
 * hasOverflow(document.querySelector('.box'));
 * // true
 */
hasScrollbar 判断元素是否出现了滚动条
/**
 * It checks if the target element has scrollbar content considering css properties
 * @param {Element} element DOM target element
 * @returns {boolean} true if the element has scrollbar
 * @example
 * <div class="box flex" style="widht: 100px;overflow: auto;">
 *  <div style="width: 200px;">
 * </div>
 * hasOverflow(document.querySelector('.box'));
 * // true
 */
hasValue 判断一个字符串是否有值
/**
 * It checks if the string has value
 * @param {string} value string to be tested
 * @returns {boolean} true if the value is valid
 */
hasValue('   ') // false
inRange 判断数字是否在两个数字中间
/**
 * It checkes if the assigned value is within the given range (inclusive)
 * @param {number} value - value to be tested
 * @param {number} min min value
 * @param {number} max max value
 * @returns {boolean} true if the number is within the range
 */
inRange(1, 2, 3 ) // false
inRange(4, 3, 5 ) // true
isDate 判断是否为日期格式
/**
 * It checks if the assigned parameter is a valid date
 * @param {any} value
 */
isDate(new Date()) // true
isArrayEmpty 判断数组是否为空
/**
 * It checks if the array is empty
 * @param {any} value array to be tested
 * @returns {boolean} true if the array is empty
 */
isArrayEmpty([]) // true
isArrayEmpty 判断对象是否为空
/**
 * It checks if the array is empty
 * @param {any} value array to be tested
 * @returns {boolean} true if the array is empty
 */
isObjectEmpty({}) // true
isImage 判断是否为图片类型(仅判断后缀名,并不能确定为真的图片)
/**
 * It checks if the given value is an imageF
 * @param {string} value string to be tested
 * @returns {boolean} true if the given value is an image
 */
isImage('ad.png') // true
isJSON 判断是否JSON格式
/**
 * It checks if the given value is an imageF
 * @param {string} value string to be tested
 * @returns {boolean} true if the given value is an image
 */
isJSON('a') // false
isMobile 判断设备是否为手机、pad等移动端设备
/**
 * It checks if the current user agent is mobile
 * @returns {boolean} true if the user agent is mobile
 */
isMobile() // true或者是false
isElement 判断是否为dom节点
/**
 * It checks if assigned parameter is an element
 * @param {any} value object to be tested
 * @returns {boolean} true if the element is a valid node
 */
<div class="box flex" style="widht: 100px;">
  <div style="width: 200px;">
</div>
isElement(document.querySelector('.box')) // true
isNumber 判断是否数字
/**
 * It checks if assigned parameter is a number
 * @param {any} value any to be tested
 * @returns {boolean} true if the value is a valid number
 */
isNumber(1) // true
isNumber('1') // true
isNumber('ss') // false
isObject 判断是否为对象
/**
 * Simple object check
 * @param {any} value object to be tested
 * @returns {boolean} true if the value is an object but not an array
 */
isObject({}) // true
isObject([]) // false
isRegex 判断是否为正则表达式
/**
 * Simple object check
 * @param {any} value object to be tested
 * @returns {boolean} true if the value is an object but not an array
 */
isRegex(/^s/) // true
isRegex('ss') // false
isString 判断是否为字符串string
/**
 * It checks if the assigned parameter is a string
 * @param {any} value value to be tested
 * @returns {boolean} true if value is a string
 */
isString('sss') // true
isString(111) // false
isString 判断是否为字符串string
/**
 * It checks if the assigned parameter is a string
 * @param {any} value value to be tested
 * @returns {boolean} true if value is a string
 */
isString('sss') // true
isString(111) // false
isURL 判断是否为合法的url地址
/**
 * It checks if the assigned value is a valid URL
 * @param {string} value string to be tested
 * @returns {boolean} true if the value is a valid URL
 */
isURL('sss') // false
isURL('[sss/ss](https://wenku.baidu.com)') // true
isCardId 是否为有效的身份证号,支持1/2代(15位/18位数字)
/**
 * @param {string} val
 * @returns {boolean}
 * @example
 * isCardId('411423198807127834');
 * // => true
 */
isCardId('sss') // false
isCardId('411423198807127834') // true
isChinese 是否为中文
/**
 * @param {string} val
 * @returns {boolean}
 * @example
 * isCardId('411423198807127834');
 * // => true
 */
isChinese('sss') // false
isChinese('是') // true
isEmpty 是否为空
/**
 * 是否为空
 * 如果a值是空对象,集合,没有可枚举属性或任何不被视为集合的类型,则返回true。
 *
 * {@link https://30secondsofcode.org/type#isempty}
 * @param val
 * @returns {boolean}
 * @example
 *
 * 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
 */
isHTML 是否html标签
/**
 * 是否为 HTML 标签
 *
 * @since 1.2.4
 * @param {string} str
 * @returns {boolean}
 * @example
 *
 * isHTML('<p>123</p>');
 *  // => true
 * isHTML('<p2>123</p2>');
 * // => true
 */
isLeapYear 是否闰年
/**
 * 是否为闰年
 *
 * @param {number} val
 * @returns {boolean}
 * @example
 *
 * isLeapYear(2000);
 * // => true
 */
isLetters 是否为字母
/**
 * 是否为字母
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isLetters('1234');
 * // => false
 * isLetters('avc');
 * // => true
 */
isSpecialChar 检查是否为特殊字符
/**
 * 检查是否为特殊字符
 * @param {string} value 正则校验的变量
 * @returns {boolean} 正则校验结果 true: 是特殊字符 false: 不是特殊字符
 * 
 * @example
 *
 * isSpecialChar('1234');
 * // => false
 * isSpecialChar('%&');
 * // => true
 */
isValidBase64Format 是否为有效的 base64格式
/**
 * 是否为有效的 base64格式
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidBase64Format('data:image/gif;base64,xxxx==')
 * => true
 */
isValidChineseName 是否为有效的中文姓名
/**
 * 是否为有效的中文姓名
 *
 * @param val
 * @returns {boolean}
 * @example
 *
 * isValidChineseName('葛二蛋');
 * // => true
 *
 * isValidChineseName('凯文·杜兰特');
 * // => true
 *
 * isValidChineseName('德克·维尔纳·诺维茨基');
 * // => true
 */
isValidChineseTelephone 是否为有效的国内座机电话
/**
 * 是否为有效的国内座机电话
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidChineseTelephone('0571-4211236');
 * // => true
 *
 * isValidChineseTelephone('0341-86091234');
 * // => true
 */
isValidEmail 是否为有效的邮箱地址
/**
 * 是否为有效的邮箱地址<br>
 * 名称允许汉字、字母、数字,域名只允许英文域名<br>
 * 中文如:杨元庆[email protected]
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidEmail('[email protected]');
 * // => true
 */
isValidEmail 是否为有效的邮箱地址
/**
 * 是否为有效的邮箱地址<br>
 * 名称允许汉字、字母、数字,域名只允许英文域名<br>
 * 中文如:杨元庆[email protected]
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidEmail('[email protected]');
 * // => true
 */
isValidEnglishName 是否为有效的英文姓名
/**
 * 是否为有效的英文姓名
 *
 * @param val
 * @returns {boolean}
 * @example
 *
 * isValidEnglishName('James');
 * // => true
 *
 * isValidEnglishName('Kevin Wayne Durant');
 * // => true
 *
 * isValidEnglishName('Dirk Nowitzki');
 * // => true
 */
isValidHexadecimalColor 是否为有效的16进制颜色
/**
 * 是否为有效的16进制颜色
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidHexadecimalColor('#f00');
 * // => true
 *
 * isValidHexadecimalColor('#fe9de8');
 * // => true
 */
isValidIPV4 是否为有效的IP v4
/**
 * 是否为有效的IP v4
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidIPV4('172.16.0.0');
 * // => true
 *
 * isValidIPV4('127.0.0.0');
 * // => true
 *
 */
isValidIPV6 是否为有效的IP v6
/**
 * 是否为有效的IP v6
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidIPV6('2031:0000:130f:0000:0000:09c0:876a:130b');
 * // => true
 *
 */
isValidSemverVersion 版本号格式必须为X.Y.Z
/**
 * 版本号格式必须为X.Y.Z
 *
 * @param {string} val
 * @returns {boolean}
 * @example
 *
 * isValidSemverVersion('16.3.10');
 * // => true
 */

Date 处理日期相关的方法

age 根据出生日期获取年龄
/**
 * It convertes date to age value
 * @param {any} value birthday
 * @returns {number} age
 */
age(new Date('1994-05-24')) // 27
compareTo 判断给定的两个日期是否相等
/**
 * It checks if the given dates are equal
 * @param {date} a date
 * @param {date} b date
 * @returns {boolean} true if the dates are equal
 */
compareTo(new Date('1994-05-24'), new Date('1994-05-24')) // true
compareDiff 返回两个时间的时间戳之差
/**
 * @param {Date | number | string} a 
 * @param {Date | number | string} b 
 * @returns {number} 
 */
compareDiff(new Date('1999-05-27'), new Date('1999-05-24')) 
toDateTime 把一个字符串变为时间格式
/**
 * It converts a string to a Date Object
 * @param {string} value string date
 * @returns {Date} date
 */

toDateTime('09-28') // Sun Dec 31 1899 09:28:00 GMT+0805 (中国标准时间)
formatDate Date 转化为指定格式的String
/**
 * Date 转化为指定格式的String<br>
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q)可以用 1-2 个占位符<br>
 * 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
 *
 * @param {string | number} date string支持形式:20160126 12:00:00,2016-01-26 12:00:00,2016.01.26 12:00:00,20160126,2016-01-26 12:00:00.0
 * @param {string} fmt
 * @returns {string}
 * @example
 *
 * formatDate(Date.now(), 'yyyy-MM-dd hh:mm:ss.S');
 * // => 2006-07-02 08:09:04.423
 *
 * formatDate(Date.now(), 'yyyy-MM-dd E HH:mm:ss');
 * // => 2009-03-10 二 20:09:04
 *
 * formatDate(Date.now(), 'yyyy-MM-dd EE hh:mm:ss');
 * // => 2009-03-10 周二 08:09:04
 *
 * formatDate(Date.now(), 'yyyy-MM-dd EEE hh:mm:ss');
 * // => 2009-03-10 星期二 08:09:04
 *
 * formatDate(Date.now(), 'yyyy-M-d h:m:s.S')
 * // => 2006-7-2 8:9:4.18
 */
// interface dynamicObj {
//   [key: string]: any
// }
formatTimeAgo 将时间转化为几天前,几小时前,几分钟前
/**
 * 将时间转化为几天前,几小时前,几分钟前
 *
 * @param {number} ms
 * @returns {*}
 * @example
 *
 * formatTimeAgo(1505232000000);
 * // => 1天前
 */
getDayOfYear 获取某个日期是当年中的第几天
/**
 * 获取某个日期是当年中的第几天
 *
 * @since 1.2.4
 * @param time
 * @returns {number}
 * @example
 *
 * getDayOfYear('2014-01-10')
 * => 10
 */
getFirstDayOfYear 获取某年的第一天
/**
 * 获取某年的第一天
 *
 * @param time
 * @returns {string}
 * @example
 *
 * getFirstDayOfYear(new Date())
 * => '2022-01-01 00:00:00
 */
getDayOfYearWeek 获取某个日期在这一年的第几周
/**
 * 获取某个日期在这一年的第几周
 *
 * @since 1.2.4
 * @param time
 * @returns {number}
 * @example
 *
 * getDayOfYearWeek('2014-01-10')
 * => 2
 */
getDayOfYearWeek 返回指定长度的天数集合
/**
 * 返回指定长度的天数集合
 * 摘自:https://segmentfault.com/a/1190000013041329
 *
 * @param  {time} 时间
 * @param  {len} 长度
 * @param  {direction} 方向:  1: 前几天;  2: 后几天;  3:前后几天  默认 3
 * @return {Array} 数组
 * @example
 *
 * getDays('2018-1-29', 6, 1)
 * // => ["2018-1-26", "2018-1-27", "2018-1-28", "2018-1-29", "2018-1-30", "2018-1-31", "2018-2-1"]
 */
getDiffDay 得到两个时间的时间差(返回天数)
/**
 * 得到两个时间的时间差(返回天数)
 *
 * @since 1.0.7
 * @param {number} startDay 开始时间戳
 * @param {number} endDay   结束时间戳
 * @returns {number}
 * @example
 *
 * getDiffDay(1501516800000, 1504195200000);
 * // => 31
 */
getMonthOfDay 获取某月有多少天
/**
 * 获取某月有多少天
 * 摘自:https://segmentfault.com/a/1190000013041329
 *
 * @param  {time} 时间
 * @return {number} 天数
 * @example
 *
 * getMonthOfDay('2018-1-29')
 * // => 31
 */
getMonths 返回指定长度的月份集合
/**
 * 返回指定长度的月份集合
 * 摘自:https://segmentfault.com/a/1190000013041329
 *
 * @param  {time} 时间
 * @param  {len} 长度
 * @param  {direction} 方向:  1: 前几个月;  2: 后几个月;  3:前后几个月  默认 3
 * @return {Array} 数组
 * @example
 *
 * getMonths('2018-1-29', 6, 1)
 * // => ["2018-1", "2017-12", "2017-11", "2017-10", "2017-9", "2017-8", "2017-7"]
 */
getYearOfDay 获取某年有多少天
/**
 * 获取某年有多少天
 *
 * @since 1.2.4
 * @param time
 * @returns {number}
 * @example
 *
 * getYearOfDay('2014')
 * => 365
 */
fromISO It converts ISO date string to Date
/**
 * It converts ISO date string to Date
 * @param {string} value utc string
 * @returns {Date} Date
 */
fromISO('+2022-05-20T07:29:48.210Z') // Fri May 20 2022 19:29:48 GMT+0800 (中国标准时间)
toISO It returns the ISO date
/**
 * It returns the ISO date (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ)
 * @param {Date} value
 * @returns {string} ISO date
 */
toISO(new Date()) //'2022-05-20T07:29:48.210Z'
toTimestamp 获取时间戳
/**
 * It returns the timestamp of the date
 * @param {Date} value
 * @returns {number} respective timestamp
 */
toTimestamp(new Date()) // 1653032030336

node dom节点相关的方法

addClass 元素添加某个class
/**
 * dom操作,元素添加某个class
 *
 * @since 1.1.5
 * @param el HTML元素
 * @param cls css类名
 * @example
 *
 * <div class="box flex"></div>
 * addClass(document.querySelector('.box'), 'flex1');
 * // => <div class="box flex flex1"></div>
 */
trigger 元素触发事件
/**
 * It manually triggers a determined event
 * @param {Element} element DOM element target
 * @param {string} element event name to be triggered
 * @param {boolean} bubbles 是否冒泡
 * <div class="box flex"></div>
 */
trigger(document.querySelector('.box'), 'click', false);
// 表示触发.box 元素click事件,不冒泡
trigger 元素是包含某个 class
/**
 * Dom 操作,元素是包含某个 class
 *
 * @since 1.1.5
 * @param el HTML元素
 * @param cls css类名
 * @returns {boolean}
 * @example
 *
 * <div class="box flex"></div>
 * hasClass(document.querySelector('.box'), 'flex');
 * // => true
 */
indexOf 找到元素是兄弟元素的第几个
/**
 * It gets the index of the element
 * @param {Element} element - DOM element target
 * @returns {number} index
 */
<div class="box flex">
    <div class="item1"></div>
    <div class="item2"></div>
    <div class="item3"></div>
</div>
indexOf(document.querySelector('.item1')) // 0
insertBefore 在目标元素前插入元素
/**
 * It inserts element before another
 * @param {Element} element - DOM element target
 * @param {Element} node - element to be inserted
 */
<div class="box flex">
    <div class="item1"></div>
    <div class="item2"></div>
</div>
insertBefore(document.querySelector('.item1'), '<div class="item3"></div>')
// <div class="box flex">
//     <div class="item3"></div>
//     <div class="item1"></div>
//     <div class="item2"></div>
// </div>
insertAfter 在目标元素后插入元素
/**
 * It inserts element after another
 * @param {Element} element - DOM element target
 * @param {Element} node - element to be inserted
 */
<div class="box flex">
    <div class="item1"></div>
    <div class="item2"></div>
</div>
insertAfter(document.querySelector('.item1'), '<div class="item3"></div>')
// <div class="box flex">
//     <div class="item1"></div>
//     <div class="item3"></div>
//     <div class="item2"></div>
// </div>
offset 获取元素距离上、左的距离
/**
 * It returns the absolute position of the element taking the scroll in considerantion
 * @param {Element} element DOM element target
 * @returns {object} { top: number, left: number }
 */
<div class="box flex">
</div>
insertAfter(document.querySelector('.box')) // { top: number, left: number }
outerHeight 获取元素占的高度
/**
 * It calculates the outer height of the element
 * @param {Element} element DOM element target
 * @returns {number} height of the element (within margin)
 */
<div class="box flex" style="height: 100px;margin-top: 20px;">
</div>
outerHeight(document.querySelector('.box')) // 120
getProperty 获取元素指定属性的值
/**
 * It returns a determined property from the given element
 * @param {Element} element DOM element target
 * @param {string} property property name
 * @returns {string} property value
 */
<div class="box flex" data-id="s1sss">
</div>
getProperty(document.querySelector('.box'), 'data-id') // s1sss
removeClass 元素删除某个 class
/**
 * Dom 操作,元素删除某个 class
 *
 * @since 1.1.5
 * @param el HTML元素
 * @param cls css类名
 * @example
 *
 * <div class="box flex"></div>
 * removeClass(document.querySelector('.box'), 'flex');
 * // => <div class="box"></div>
 */
scrollToTop 滚动到顶部
/**
 * 滚动到顶部
 * 使用document.documentElement.scrollTop或document.body.scrollTop获取到顶部的距离。从顶部滚动一小部分距离。
 使用window.requestAnimationFrame()来滚动。
 *
 * @since 1.2.1
 * @example
 *
 * scrollToTop();
 */
inViewport 判断元素是否在可视范围内
/**
 * It checks whether the target element is in viewport
 * @param {Element} element DOM element target
 * @returns {boolean} true if the element is in viewport
 */
<div class="box flex" style="height: 100px;margin-top: 20px;">
</div>
inViewport(document.querySelector('.box')) // true || false
find 根据给定的元素或其本身遍历查找元素
/**
 * It walks the tree to find the element based on the given selector or itself
 * @param {Element} element DOM root element
 * @param {string} selector DOM selector
 * @param {boolean} all (default false)
 * @returns {Element} element that matches the selector and if all is true, it might returns more than one element
 */
<div class="box flex">
    <div class="item1"></div>
    <div class="item2"></div>
</div>
find(document.querySelector('.box'), '.item1', true)
//  <div class="item1"></div>
//  <div class="item2"></div>
closest 找到给定元素的父元素
/**
 * It moves backwards on the tree throught the parent nodes
 * @param {Element} element DOM root element
 * @param {string} selector DOM selector
 * @returns {Element} if finds an element which matches the selector, otherwise returns null
 */
<div class="box flex">
    <div class="item1"></div>
    <div class="item2"></div>
</div>
matches 递归搜索与给定选择器匹配的元素
/**
 * It searchs for elements that matches the given selector (recursively)
 * @param {Element} element DOM root element
 * @param {string} selector DOM selector
 * @returns {Element} if finds an element which matches the selector, otherwise returns null
 */
forward 它在树上通过兄弟元素向前移动
/**
 * It moves forward on the tree throught the sibling elements
 * @param {Element} element DOM root element
 * @param {string} selector DOM selector
 * @returns {Element} if finds an element which matches the selector, otherwise returns null
 */
backward 它在树上通过兄弟元素向后移动
/**
 * It moves backward on the tree throught the sibling elements
 * @param {Element} element DOM root element
 * @param {string} selector DOM selector
 * @returns {Element} if finds an element which matches the selector, otherwise returns null
 */

number 数字类型相关处理方法

changeMoneyToChinese 数字金额大写转换
/**
 * 数字金额大写转换
 *
 * @since 1.2.5
 * @param n
 * @returns {string}
 * @example
 *
 * changeMoneyToChinese(100111);
 * => "壹拾万零壹佰壹拾壹元整"
 *
 * changeMoneyToChinese(7.52);
 * => "柒元伍角贰分"
 *
 * changeMoneyToChinese(951434677682.00);
 * => "玖仟伍佰壹拾肆亿叁仟肆佰陆拾柒万柒仟陆佰捌拾贰元整"
 */
formatNumber 格式化数字、金额、千分位、保留几位小数、舍入舍去
/**
 * 格式化数字、金额、千分位、保留几位小数、舍入舍去
 *
 * @since 1.0.7
 * @param number 要格式化的数字
 * @param decimals 保留几位小数
 * @param decPoint 小数点符号
 * @param thousandsSep 千分位符号
 * @param roundTag 舍入参数,默认 'ceil' 向上取,'floor'向下取,'round' 四舍五入
 * @returns {XML|void|*|string}
 * @example
 *
 * formatNumber(2, 2, '.', ',');
 * // => 2.00
 */
getRandomInt 获取max与min之间的随机数
/**
 * 获取max与min之间的随机数
 *
 * @param {number} min
 * @param {number} max
 * @returns {*}
 * @example
 *
 * getRandomInt(1, 9);
 * // => 2
 */
minmax 获取两个参数组成的[最小值, 最大值]数组
/**
 * It checks if the given values are valid and garantizes that min < max
 * @param {number} min min value
 * @param {number} max max value
 * @returns {array} [min, max]
 */
numberToChinese 数字转换成中文的大写数字
/**
 * 数字转换成中文的大写数字
 *
 * @since 1.2.5
 * @param num
 * @returns {string}
 * @example
 *
 * numberToChinese(10001010);
 * => "一千万一千一十"
 */
pad 给数字添加前置的0
/**
 * It adds leading zeros
 * @param {number} value number to be filled with leading zeros
 * @param {number} size result length (default 2)
 * @returns {string} value if the leading zeros
 */
pad(3, 3) //'003'
prettyBytes 将字节转换成友好格式,如Bytes,KB,MB
/**
 * 将字节转换成友好格式,如Bytes,KB,MB
 *
 * @param num
 * @param precision 3位数字的默认精度
 * @param addSpace 默认情况下在数字和单位之间添加空格
 * @returns {string}
 * {@link https://www.30secondsofcode.org/js/s/pretty-bytes}
 * @example
 *
 * prettyBytes(10000)
 * // => '1 KB'
 * // prettyBytes(-27145424323.5821, 5);
 * // => '-27.145 GB'
 * // prettyBytes(123456789, 3, false);
 * // => '123MB'
 */
preZeroFill 对整数进行前置补0
/**
 * 对整数进行前置补0
 *
 * @param {number} num 数值
 * @param {number} size 要补0的位数
 * @returns {string}
 * @example
 *
 * preZeroFill(12, 3);
 * // => 012
 */
random 获取两个数之间的随机数
/**
 * It generates a random value (decimal) between min and max
 * @param {number} min min value (default MIN_VALUE)
 * @param {number} max max value (default MAX_VALUE)
 * @returns {number} random value
 */
randomDecimal (1, 5) // 1.4016161022088092
time 将秒转换为天、小时、分钟、秒
/**
 * It converts seconds to days, hours, minutes, seconds
 * @param {number} value time to be converted (in seconds)
 * @returns {any} an object containing the count of days, hours, minutes and seconds or the value itself
 */
time(11111) // {hour: 3, min: 5, sec: 11}
toTimeString 将秒转换时间字符串
/**
 * It converts seconds to time string (00:00:00)
 * @param {number} value time to be converted (in seconds)
 * @returns {string} an object containing the count of days, hours, minutes and seconds as string
 */
toTimeString(1111) // '18:31'
strip 将数字去掉到最接近的右边数字
/**
 * 将数字去掉到最接近的右边数字
 * @param {number}
 * @returns {number}
 */
strip(0.09999999999999998) // = 0.1
plus 数字求和
/**
 * addition, num + num2 + num3, two numbers is required at least
 * @param {number}
 * @returns {number}
 */
plus(0.1, 0.2) // = 0.3, not 0.30000000000000004
minus 数字求差
/**
 * subtraction, num1 - num2 - num3
 * @param {number}
 * @returns {number}
 */
minus(1.0, 0.9) // = 0.1, not 0.09999999999999998
times 数字积运算
/**
 * multiplication, num1 * num2 * num3
 * @param {number}
 * @returns {number}
 */
times(3, 0.3) // = 0.9, not 0.8999999999999999
divide 数字商运算
/**
 * division, num1 / num2 / num3
 * @param {number}
 * @returns {number}
 */
divide(1.21, 1.1) // = 1.1, not 1.0999999999999999
round 基于比率舍入数字
/**
 * round a number based on ratio
 * @param {number}
 * @returns {number}
 */
round(0.105, 2) // = 0.11, not 0.1

object 对象相关的方法

createNamespace 创建命名空间
/* Creates a name namespace.
 *  Example:
 *  var taskService = createNamespace(ics, 'services.task');
 *  taskService will be equal to ics.services.task
 *  first argument (root) must be defined first
 ************************************************************/
deepMerge 将两个对象,深度合并
/**
 * Deep merge two objects
 * @param {object} original original object
 * @param {object} params object to be merged
 * @returns {object} merged object
 */

deepMerge({a: 1, b: {x: 2}}, {a: 1, b: {y: 2}}) // {a: 1, b: {x: 2, y: 2}}
deepClone 深层克隆对象
/**
 * 深层克隆对象
 *
 * @param obj
 * @returns {*}
 * @example
 *
 * const a = { foo: 'bar', obj: { a: 1, b: 2 } };
 * const b = deepClone(a);
 * // => a !== b, a.obj !== b.obj
 */
extend 将from所有的键值对都添加到to上面去,返回to
/**
 * 将from所有的键值对都添加到to上面去,返回to
 *
 * @param {Object} to
 * @param {Object} from
 * @returns {*}
 * @example
 *
 * const from = {mobile: '15858264903', nickname: 'liwb'};
 * const to = {nickname: 'cklwb'};
 *
 * extend(to, from);
 * // => {nickname: "liwb", mobile: "15858264903"}
 */
getIn 深度获取对象值
/**
 * 主动防御
 * 对于我们操作的数据,尤其是由 API 接口返回的,时常会有一个很复杂的深层嵌套的数据结构。为了代码的健壮性,很多时候需要对每一层访问都作空值判断,就像这样:
 props.user &&
 props.user.posts &&
 props.user.posts[0] &&
 props.user.posts[0].comments &&
 props.user.posts[0].comments[0]
 代码看起来相当不美观,因此提供了一个非常简洁明了的原生的方式。
 *
 * @param p 属性列表
 * @param o 对象
 * @returns {*} 如果正常访问到,则返回对应的值,否则返回 null。
 * @example
 *
 * var props = {
 *  user: {
 *    post: [{
 *      comments: 'test'
 *    }]
 *  }
 * };
 * getIn(['user', 'post', 0, 'comments'], props);
 * // => test
 */
objectFromPairs 数组转换为键值对的对象
/**
 * 数组转换为键值对的对象
 *
 * @since 1.2.1
 * @param array
 * @returns {*}
 * @example
 *
 * objectFromPairs([['a',1],['b',2]]);
 * // => {a: 1, b: 2}
 */
objectToPairs 对象转化为键值对
/**
 * 对象转化为键值对
 * 使用 Object.keys() 和 Array.map() 遍历对象的键并生成一个包含键值对的数组。
 * 
 * @param obj
 * @returns {any[][]}
 * @example
 *
 * objectToPairs({ a: 1, b: 2 });
 * // => [['a',1],['b',2]]
 */
parser 键值对转化为对象
/**
 * It parses a form to pair-value object
 * @param {[Object]} form form array
 * @returns {Object} form oject or {} if there is no values to parse
 * @example
 *
 * parser([['a',1],['b',2]]);
 * // => { a: 1, b: 2 }
 */
swap 交换数组中的两个值
/**
 * It swaps two elements inside an array
 * @param {object} elements array
 * @param {number} from index
 * @param {number} to index
 * @returns {object} new array
 */
swap([1,2,3,4]) // [1, 4, 3, 2]

string 字符串方法

CamelCasetoKebab 驼峰转短横线
CamelCasetoKebab('carId') // car-id
KebabtoCamelCase 短横线转小驼峰
KebabtoCamelCase('car-id') // carId
KebabtoPascalCase 短横线转大驼峰
KebabtoPascalCase('car-id') // CarId
capitalizes 大写首字母
/**
 * It capitalizes the given string
 * @param {string} value value to be capitalized
 * @returns {string} captalized value
 */
capitalizes(car) // Car
toRGB 将hex颜色转为rgb颜色
/**
 * It converts an Hex color to a RGB color
 * @param {string} value - Hex color with or without `#`
 * @return {object?} { r: number, g: number, b: number } or undefined if does not match
 */
toRGB('#4e6ef2') // { r: 78, g: 110, b: 242 }
toHex 将rgb颜色转为hex颜色
/**
 * It converts an RGB color to an Hex color
 * @param {string} value RGB color
 * @param {string} prefix default value '#'
 * @return {string} Hex color or the entered value
 */
toHex ('78,110,242') // #4E6EF2
getContrast 为给定背景确定最合适的文本颜色
/**
 * It determines the most appropriate text color for the given background
 * @param {string} value - background color (RGB color string)
 * @param {string} light color when light (default #fff)
 * @param {string} dark color when dark (default #000)
 * @returns {string} the color with the most appropriate contrast
 */
getContrast ({ r: 78, g: 110, b: 242 }) //'#fff'
filesize 获取文件大小
/**
 * It converts filesize from bytes to gigabytes, megabytes, kilobytes and bytes
 * @param {number} value value to be converted to string
 * @param {number} base default 1024
 * @returns {string} string representation of the filesize
 */
formatDateToTimeStamp 获取指定时间unix时间戳
/**
 * 获取指定时间unix时间戳
 *
 * @param {string} time
 * @returns {number}
 * @example
 *
 * formatDateToTimeStamp('20160126 12:00:00');
 * // => 1453780800000
 *
 * formatDateToTimeStamp('2016-01-26 12:00:00');
 * // => 1453780800000
 *
 * formatDateToTimeStamp('2016.01.26 12:00:00');
 * // => 1453780800000
 *
 * formatDateToTimeStamp('20160126');
 * // => 1453737600000
 *
 * formatDateToTimeStamp('2016-01-26 12:00:00.0');
 * // => 1453780800000
 */
formatMoney 用符号(默认为逗号)格式化金钱
/**
 * 用符号(默认为逗号)格式化金钱
 *
 * @param {string} val
 * @param {string} symbol 默认`,`
 * @returns {string|*|XML|void}
 * @example
 *
 * formatMoney('1234567890');
 * // => 1,234,567,890
 */
formatPhone 手机号码中间部分替换成指定符号
/**
 * 手机号码中间部分替换成指定符号
 *
 * @param {string} phone
 * @param {string} symbol 默认为`*`
 * @returns {string|*|XML|void}
 * @example
 *
 * formatPhone('15858264903');
 * // => 158****4903
 */
formatString
/* Formats a string just like string.format in C#.
 *  Example:
 *  formatString('Hello {0}','Tuana') = 'Hello Tuana'
 ************************************************************/
generateGUID 生成guid
/**
 * 生成guid
 *
 * @returns {string}
 * @example
 *
 * generateGUID();
 * // => 1e508ed6-6177-498d-c2a3-467f546db6ab
 */
getImgBase64 获取图片的base64 url
/**
 * 获取图片的base64 url
 * @param {string} url 图片url
 * @returns {Promise} 图片base64信息
 */
getLocationHrefParam 获取location.href参数
/**
 * 获取location.href参数
 *
 * @param {string} name
 * @returns {*}
 * @example
 *
 * window.location.href = 'http://www.baidu.com/?a=1&b=2';
 *
 * getLocationHrefParam('a');
 * // => 1
 */
getLocationSearchParam 获取location.search的参数
/**
 * 获取location.search的参数
 *
 * @param {string} name
 * @returns {*}
 * @example
 *
 * window.location.href = 'http://www.baidu.com/?a=1&b=2';
 *
 * getLocationSearchParam('a');
 * // => 1
 */
getURLParameters 获取网址参数
/**
 * 获取网址参数
 * @param {string} url
 * @returns {{}} 返回包含当前URL参数的对象。
 * @example
 *
 * getURLParameters('http://url.com/page?name=Adam&surname=Smith');
 * => // {name: 'Adam', surname: 'Smith'}
 */
htmlDecode html字符解码
/**
 * html字符解码
 *
 * @param {string} str
 * @returns {string}
 * @example
 *
 * htmlDecode('&lt;script&gt;');
 * // => <script>
 */
htmlEncode html字符编码
/**
 * html字符编码
 *
 * @param {string} str
 * @returns {string}
 * @example
 *
 * htmlEncode('<script>');
 * // => &lt;script&gt;
 */
formattedJSON 转化为json字符串
/**
 * It makes JSON string "prettier"
 * @param {string} value JSON to be formatted
 * @param {number} spaces indentation
 * @returns {string} formatted JSON
 */
md5 md5加密
/**
 * @description:md5加密
 * @param {string} message 字符串
 * @return {sting} MD5加密字符串
 */
normalize 去掉读音符号
/**
 * It removes all the accentuation
 * @param {string} value to be replaced
 * @returns {string} formatted value
 */
normalize('ÁÀÂÃÄ') // AAAAA
objectId 生成对象的唯一id
/**
 * It generates ObjectId (mongodb)
 * @param {Math} math
 * @param {DateConstructor} date
 * @param {Function} callback
 * @returns {string}
 */
objectId() // 628756d34d6d7a5336ffa473
replaceAll 替换字符串
/* Find and replaces a string (search) to another string (replacement) in
 *  given string (str).
 *  Example:
 *  replaceAll('This is a test string', 'is', 'X') = 'ThX X a test string'
 ************************************************************/
toCamelCaseVar 下划线转换小驼峰
/**
 * 下划线转换小驼峰
 *
 * @param {string} variable
 * @returns {string}
 * @example
 *
 * toCamelCaseVar('get_account_list');
 * // => getAccountList
 */
generateCode 生成一个指定长度的只有数字的token
/**
 * It generates a token with a determined length with only numbers (0-9)
 * @param {number} len length of the code
 * @returns {string} generated token
 */
generateCode(5) // '27565'
generateKey 生成一个指定长度的只有数字(不含0)和字母的token
/**
 * It generates a token with a determined length with only letters and numbers excluding zero
 * @param {number} len length of the code
 * @returns {string} generated token
 */
generateKey (5) // 'jYSPJ'
toNonExponential 科学计数法转化为数值字符串形式
/**
 * 科学计数法转化为数值字符串形式
 *
 * @param {number} num
 * @returns {string}
 * @example
 *
 * toNonExponential(3.3e-7);
 * => // "0.00000033"
 *
 * toNonExponential(3e-7);
 * => // "0.0000003"
 *
 * toNonExponential(1.401e10);
 * => // "14010000000"
 *
 * toNonExponential(0.0004);
 * => // "0.0004"
 */
toNumber 转数字
/**
 * 转数字
 *
 * @param val
 * @returns {*|number}
 * @example
 *
 * toNumber(1.2);
 * => // 1.2
 */
toUnderlineVar 驼峰转换下划线
/**
 * 驼峰转换下划线
 *
 * @param {string} variable
 * @returns {string}
 * @example
 *
 * toUnderlineVar('getAccountList');
 * // => get_account_list
 */
toZhCN 把字符串或数字转换为中文大写的金额
/**
 * toZhCN 把字符串转成以分为单位的整数。
 *
 * @param {number|string} num 金额
 * @returns {string} 中文大写的金额, 标准会计格式
 * @example
 *
 * toZhCN(500.3);
 * // => 伍佰元叁角整
 */
allTrim 去除字符串所有空格
trim 去除字符串前后空格
leftTrim 去除字符串前空格
rightTrim 去除字符串后空格
truncateString 从首位开始截取字符串
/**
 * truncateString 从首位开始截取字符串
 *
 * @param {string} 
 * @param {number} maxLength 截取长度
 * @returns {string} 截取的字符串
 */
truncateString('abc', 2) // 'ab'
truncateStringWithPostfix 从首位开始截取字符串并拼接指定字符串
/**
 * truncateStringWithPostfix 从首位开始截取字符串并拼接指定字符串
 *
 * @param {string} 
 * @param {number} maxLength 截取长度
 * @param {string} postfix 拼接字符串
 * @returns {string} 拼接后的字符串
 */
truncateStringWithPostfix('abc', 1, 'xyz') // x
uniqueId 生成唯一的ID
/**
 * It generates a random and unique value
 * @returns {string} unique value
 */
uniqueId () // 'fsfoyh57hkw'
getStrokeCode 获取五笔码
/**
 * @returns {string}  value
 */
getStrokeCode ('你好') // 'WV'
getFirstSpell getFullSpell 拼音码首拼、全拼
/**
 * @returns {string}  value
 */
getFirstSpell ('你好') // 'NH'
getFullSpell ('你好') // 'nihao'
URLJoin 拼接url
/**
 * URLJoin
 *
 * @param args
 * @returns {string}
 * @description
 * Joins all given URL segments together, then normalizes the resulting URL.

 Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).
 * @example
 *
 * URLJoin('http://www.google.com', 'a', '/b/cd', '?foo=123', '?bar=foo');
 * // => 'http://www.google.com/a/b/cd?foo=123&bar=foo'
 */
雪花算法,生成id
/**
 * URLJoin
 *
 * @param workerId 标识ID
 * @param dataCenterId 机器ID
 * @returns {string}
 * @description
 * Joins all given URL segments together, then normalizes the resulting URL.

 Use String.prototype.join('/') to combine URL segments, then a series of String.prototype.replace() calls with various regexps to normalize the resulting URL (remove double slashes, add proper slashes for protocol, remove slashes before parameters, combine parameters with '&' and normalize first parameter delimiter).
 * @example
 **/
    const { SnowFlake } = string
    const snowflake = new SnowFlake(1, 1, 0)
    snowflake.nextId()
校验身份证
/**
 * URLJoin
 *
 * @param id 身份证号
 * @returns   {
    valid: true,
    validMsg: '',
    birthday: '',
    sex: '',
    age: 0
  }
 * @description
 * @example
 **/
    validIdNo('350781196403072206')

system 系统相关方法

buildQueryString 设置cookie
/**
 * Sets a cookie value for given key.
 * This is a simple implementation created to be used by ics.
 * Please use a complete cookie library if you need.
 * @param {string} key
 * @param {string} value
 * @param {Date} expireDate (optional). If not specified the cookie will expire at the end of session.
 * @param {string} path (optional)
 */
buildQueryString('name', 'dengliu2', new Date('2024-06-28'), 'system')
getCookieValue 获取cookie
/**
 * Gets a cookie with given key.
 * This is a simple implementation created to be used by ics.
 * Please use a complete cookie library if you need.
 * @param {string} key
 * @returns {string} Cookie value or null
 */
getCookieValue('name') // 'dengliu2;path=system'
deleteCookie 删除cookie
/**
 * @param {string} key
 */
deleteCookie('name')
getBrowser 获取浏览器的类型和版本号
/**
 * 获取浏览器的类型和版本号
 *
 * @returns {{type: string, version: string}}
 * @example
 *
 * getBrowser();
 * // => {type: "chrome", version: "60.0.3112.101"}
 */
getDevice 获取移动设备信息,如是否是iOS,android等
/**
 * 获取移动设备信息,如是否是iOS,android等
 *
 * @returns {{}}
 * @example
 *
 * getDevice();
 * // => {"androidChrome":false,"ipad":false,"iphone":true,"android":false,"ios":true,"os":"ios","osVersion":"9.1","webView":null}
 */
getPixelRatio 获取设备像素比
/**
 * 获取设备像素比
 *
 * @returns {number}
 * @example
 *
 * // window.navigator.appVersion(5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1)
 * getPixelRatio();
 * // => 2
 */
htmlEscape html标签转义
/**
 * Escape HTML to help prevent XSS attacks.
 */
htmlEscape('<>') // '&lt;&gt;'
photoCompress 图片压缩
/**
 * 图片压缩
 * @param  {string}   file [压缩文件]
 * @param  {object}   obj [压缩参数]
 * @param  {function} cb   [回调函数]
 * @return {string}        [返回压缩前和压缩后的格式]
 */