Escape regular expression (转义正则表达式)
使用 replace()
来转义特殊字符。
- const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- // escapeRegExp('(test)') -> \\(test\\)
Get native type of value (获取原生类型的值)
返回值小写的构造函数名称,如果值为 undefined 或 null ,则返回 “undefined” 或 “null”。
- const getType = v =>
- v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
- // getType(new Set([1,2,3])) -> "set"
Hexcode to RGB (Hex转RGB)
使用Array.slice()
, Array.map()
和 match()
将十六进制颜色代码(前缀为#
)转换为RGB值的字符串。
- const hexToRgb = hex => `rgb(${hex.slice(1).match(/.{2}/g).map(x => parseInt(x, 16)).join()})`
- // hexToRgb('#27ae60') -> 'rgb(39,174,96)'
Is array(是否为数组)
使用 Array.isArray()
来检查一个值是否为一个数组。
- const isArray = val => !!val && Array.isArray(val);
- // isArray(null) -> false
- // isArray([1]) -> true
Is boolean(是否为布尔值)
使用 typeof
来检查一个值是否为一个布尔值。
- const isBoolean = val => typeof val === 'boolean';
- // isBoolean(null) -> false
- // isBoolean(false) -> true
Is function(是否为函数)
使用 typeof
来检查一个值是否为一个函数。
- const isFunction = val => val && typeof val === 'function';
- // isFunction('x') -> false
- // isFunction(x => x) -> true
Is number(是否为数字)
使用 typeof
来检查一个值是否为一个数字。
- const isNumber = val => typeof val === 'number';
- // isNumber('1') -> false
- // isNumber(1) -> true
Is string(是否为字符串)
使用 typeof
来检查一个值是否为一个字符串。
- const isString = val => typeof val === 'string';
- // isString(10) -> false
- // isString('10') -> true
Is symbol(是否为symbol)
使用 typeof
来检查一个值是否为一个 symbol 。
- const isSymbol = val => typeof val === 'symbol';
- // isSymbol('x') -> false
- // isSymbol(Symbol('x')) -> true
Measure time taken by function (计算函数执行所花费的时间)
使用 console.time()
和 console.timeEnd()
来测量开始和结束时间之间的差,以确定回调执行的时间。
- const timeTaken = callback => {
- console.time('timeTaken');
- const r = callback();
- console.timeEnd('timeTaken');
- return r;
- };
- // timeTaken(() => Math.pow(2, 10)) -> 1024
- // (logged): timeTaken: 0.02099609375ms
Number to array of digits (将数字转化为整数数组)
将数字转换为字符串,使用 split()
来转换构建一个数组。 使用 Array.map()
和 parseInt()
将每个值转换为整数。
- const digitize = n => (''+n).split('').map(i => parseInt(i));
- // digitize(2334) -> [2, 3, 3, 4]
Ordinal suffix of number (数字序号的后缀)
使用模运算符(%
)来查找各位和十位的值。查找哪些序号模式数字匹配。如果数字在十位模式中找到,请使用十位的序数。
- const toOrdinalSuffix = num => {
- const int = parseInt(num), digits = [(int % 10), (int % 100)],
- ordinals = ['st', 'nd', 'rd', 'th'], oPattern = [1, 2, 3, 4],
- tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
- return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) ? int + ordinals[digits[0] - 1] : int + ordinals[3];
- };
- // toOrdinalSuffix("123") -> "123rd"
Random integer in range (在指定的范围内生成一个随机整数)
使用 Math.random()
生成一个随机数并将其映射到所需的范围,使用 Math.floor()
使其成为一个整数。
- const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
- // randomIntegerInRange(0, 5) -> 2
Random number in range (在指定的范围内生成一个随机数)
使用 Math.random()
生成一个随机值,使用乘法将其映射到所需的范围。
- const randomInRange = (min, max) => Math.random() * (max - min) + min;
- // randomInRange(2,10) -> 6.0211363285087005
RGB to hexadecimal(RGB转hex)
使用按位左移运算符(<<
)和 toString(16)
将给定的RGB参数转换为十六进制字符串,然后使用 padStart(6,'0')
得到一个6位的十六进制值。
- const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
- // rgbToHex(255, 165, 1) -> 'ffa501'
Swap values of two variables (交换两个变量的值)
使用数组解构来交换两个变量之间的值。
- [varA, varB] = [varB, varA];
- // [x, y] = [y, x]
URL parameters(网址参数)
通过适当的正则表达式,使用 match()
来获得所有的键值对, Array.reduce()
来映射和组合成一个单一的对象。将 location.search
作为参数传递给当前 url
。
- const getUrlParameters = url =>
- url.match(/([^?=&]+)(=([^&]*))/g).reduce(
- (a, v) => (a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1), a), {}
- );
- // getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
UUID generator (UUID生成器)
使用 crypto
API 生成符一个 UUID,符合RFC4122 版本 4 。
- const uuid = _ =>
- ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
- (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
- );
- // uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
Validate email(邮箱验证)
使用正则表达式来检查电子邮件是否有效。如果电子邮件有效,则返回 true
,否则返回false
。
- const validateEmail = str =>
- /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/.test(str);
- // validateEmail([email protected]) -> true
Validate number (数字验证)
使用 !isNaN
和 parseFloat()
来检查参数是否是一个数字。使用 isFinite()
来检查数字是否是有限数。使用 Number()
来检查强制转换是否成立。
- const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;
- // validateNumber('10') -> true
Value or default (值或者默认值)
返回 value ,如果传递的值是 falsy
,则返回默认值。
- const valueOrDefault = (value, d) => value || d;
- // valueOrDefault(NaN, 30) -> 30