摘要:在數(shù)組中循環(huán)使用將數(shù)組的第一個(gè)元素除去直到函數(shù)的返回值為。使用匿名內(nèi)部函數(shù)范圍來(lái)聲明未定義的內(nèi)存空間使用閉包來(lái)存儲(chǔ)返回值。返回頂部從數(shù)組中移除給定函數(shù)返回的元素使用查找返回值的數(shù)組元素和以使用刪除元素。使用執(zhí)行從右向左的函數(shù)組合。
Util.js (持續(xù)更新中...)
項(xiàng)目地址: https://github.com/dragonir/U...項(xiàng)目描述
Util.js 是對(duì)常用函數(shù)的封裝,方便在實(shí)際項(xiàng)目中使用,主要內(nèi)容包含:數(shù)組類、瀏覽器類、日期類、函數(shù)類、數(shù)學(xué)類、媒體類、節(jié)點(diǎn)類、對(duì)象類、字符串類、類型檢測(cè)類、正則表達(dá)式類等內(nèi)容。使用方法 1. 引入Bable transpiler以保證支持ES6
或引入壓縮版
2. 引入工具函數(shù)文件Util.js或引入壓縮版
3. 使用舉例_Example 1_: 通過(guò)調(diào)用 isArray() 方法來(lái)判斷數(shù)值是否為數(shù)組
var arr = []; var obj = {}; console.log(Util.isArray(arr)); // true console.log(Util.isArray(obj)); // false
_Example 2_: 通過(guò)調(diào)用 extendHex() 方法將3位色值轉(zhuǎn)換為6位色值
console.log(Util.extendHex("#03f")); // #0033ff console.log(Util.extendHex("05a")); // #0055aa console.log(Util.extendHex("#03c03c")); // #03c03c項(xiàng)目目錄
文件名 | 描述 |
---|---|
Util.js | 工具函數(shù)主文件 |
Util.min.js | 工具函數(shù)壓縮版 |
RegExp.js | 正則表達(dá)式封裝 |
RegExp.min.js | 正則表達(dá)式封裝壓縮版 |
browser.js | ES6向后兼容 |
browser.min.js | ES6向后兼容 |
string-utils.js | 字符串工具函數(shù)(待整合) |
00. 常用正則表達(dá)式示例-RegExp.html | 正則表達(dá)式測(cè)試演示 |
01. 常用工具函數(shù)示例-Util-數(shù)組類.html | 數(shù)組類測(cè)試演示 |
02. 常用工具函數(shù)示例-Util-瀏覽器類.html | 瀏覽器類測(cè)試演示 |
03. 常用工具函數(shù)示例-Util-日期類.html | 日期類測(cè)試演示 |
04. 常用工具函數(shù)示例-Util-函數(shù)類.html | 函數(shù)類測(cè)試演示 |
05. 常用工具函數(shù)示例-Util-數(shù)學(xué)類.html | 數(shù)學(xué)類測(cè)試演示 |
06. 常用工具函數(shù)示例-Util-媒體類.html | 媒體類測(cè)試演示 |
07. 常用工具函數(shù)示例-Util-節(jié)點(diǎn)類.html | 設(shè)為首頁(yè) |
08. 常用工具函數(shù)示例-Util-對(duì)象類.html | 對(duì)象類測(cè)試演示 |
09. 常用工具函數(shù)示例-Util-字符串.html | 字符串測(cè)試演示 |
10. 常用工具函數(shù)示例-Util-其他實(shí)用函數(shù).html | 其他實(shí)用函數(shù)測(cè)試演示 |
11. 常用工具函數(shù)示例-Util-類型檢測(cè).html | 類型檢測(cè) |
README.MD | 項(xiàng)目描述文件 |
logo.png | 項(xiàng)目圖標(biāo) |
感謝原作者分享了大量有用的Javascript片段,我在其基礎(chǔ)上將其封裝為一個(gè)文件方便使用。
源項(xiàng)目:https://github.com/Chalarangelo/30-seconds-of-code內(nèi)容目錄翻譯項(xiàng)目:http://caibaojian.com/30-seconds-of-code.html
以下是項(xiàng)目具體內(nèi)容以及詳細(xì)注釋,可通過(guò)查詢找到自己需要的函數(shù)。數(shù)組類
arrayMax
arrayMin
chunk
compact
countOccurrences
deepFlatten
difference
distinctValuesOfArray
dropElements
everyNth
filterNonUnique
flatten
flattenDepth
groupBy
head
initial
initializeArrayWithRange
initializeArrayWithValues
intersection
last
mapObject
nthElement
pick
pull
remove
sample
shuffle
similarity
symmetricDifference
tail
take
takeRight
union
without
zip
瀏覽器bottomVisible
currentURL
elementIsVisibleInViewport
getScrollPosition
getURLParameters
redirect
scrollToTop
時(shí)間getDaysDiffBetweenDates
JSONToDate
toEnglishDate
函數(shù)chainAsync
compose
curry
functionName
pipe
promisify
runPromisesInSeries
sleep
數(shù)學(xué)arrayAverage
arraySum
collatz
digitize
distance
factorial
fibonacci
gcd
hammingDistance
isDivisible
isEven
lcm
median
palindrome
percentile
powerset
randomIntegerInRange
randomNumberInRange
round
standardDeviation
媒體speechSynthesis
節(jié)點(diǎn)JSONToFile
readFileLines
對(duì)象cleanObj
objectFromPairs
objectToPairs
shallowClone
truthCheckCollection
字符串anagrams
capitalize
capitalizeEveryWord
escapeRegExp
fromCamelCase
reverseString
sortCharactersInString
toCamelCase
truncateString
工具coalesce
coalesceFactory
extendHex
getType
hexToRGB
isArray
isBoolean
isFunction
isNumber
isString
isSymbol
RGBToHex
timeTaken
toOrdinalSuffix
UUIDGenerator
validateEmail
validateNumber
數(shù)組? 返回頂部
arrayMax返回?cái)?shù)組中的最大值。
將Math.max()與擴(kuò)展運(yùn)算符 (...) 結(jié)合使用以獲取數(shù)組中的最大值。
const arrayMax = arr => Math.max(...arr); // arrayMax([10, 1, 5]) -> 10
? 返回頂部
arrayMin返回?cái)?shù)組中的最小值。
將Math.min()與擴(kuò)展運(yùn)算符 (...) 結(jié)合使用以獲取數(shù)組中的最小值。
const arrayMin = arr => Math.min(...arr); // arrayMin([10, 1, 5]) -> 1
? 返回頂部
chunk將數(shù)組塊劃分為指定大小的較小數(shù)組。
使用Array.from()創(chuàng)建新的數(shù)組, 這符合將生成的區(qū)塊數(shù)。使用Array.slice()將新數(shù)組的每個(gè)元素映射到size長(zhǎng)度的區(qū)塊。如果原始數(shù)組不能均勻拆分, 則最終的塊將包含剩余的元素。
const chunk = (arr, size) => Array.from({length: Math.ceil(arr.length / size)}, (v, i) => arr.slice(i * size, i * size + size)); // chunk([1,2,3,4,5], 2) -> [[1,2],[3,4],[5]]
? 返回頂部
compact從數(shù)組中移除 falsey 值。
使用Array.filter()篩選出 falsey 值 (false、null、0、""、undefined和NaN).
const compact = (arr) => arr.filter(Boolean); // compact([0, 1, false, 2, "", 3, "a", "e"*23, NaN, "s", 34]) -> [ 1, 2, 3, "a", "s", 34 ]
? 返回頂部
countOccurrences計(jì)算數(shù)組中值的出現(xiàn)次數(shù)。
使用Array.reduce()在每次遇到數(shù)組中的特定值時(shí)遞增計(jì)數(shù)器。
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0); // countOccurrences([1,1,2,1,2,3], 1) -> 3
? 返回頂部
deepFlatten深拼合數(shù)組。
使用遞歸。使用Array.concat()與空數(shù)組 ([]) 和跨頁(yè)運(yùn)算符 (...) 來(lái)拼合數(shù)組。遞歸拼合作為數(shù)組的每個(gè)元素。
const deepFlatten = arr => [].concat(...arr.map(v => Array.isArray(v) ? deepFlatten(v) : v)); // deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
? 返回頂部
difference返回兩個(gè)數(shù)組之間的差異。
從b創(chuàng)建Set, 然后使用Array.filter() on 只保留a b中不包含的值.
const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); }; // difference([1,2,3], [1,2,4]) -> [3]
? 返回頂部
distinctValuesOfArray返回?cái)?shù)組的所有不同值。
使用 ES6 Set和...rest運(yùn)算符放棄所有重復(fù)的值。
const distinctValuesOfArray = arr => [...new Set(arr)]; // distinctValuesOfArray([1,2,2,3,4,4,5]) -> [1,2,3,4,5]
? 返回頂部
dropElements移除數(shù)組中的元素, 直到傳遞的函數(shù)返回true。返回?cái)?shù)組中的其余元素。
在數(shù)組中循環(huán), 使用Array.shift()將數(shù)組的第一個(gè)元素除去, 直到函數(shù)的返回值為true。返回其余元素。
const dropElements = (arr, func) => { while (arr.length > 0 && !func(arr[0])) arr.shift(); return arr; }; // dropElements([1, 2, 3, 4], n => n >= 3) -> [3,4]
? 返回頂部
everyNth返回?cái)?shù)組中的每個(gè)第 n 個(gè)元素。
使用Array.filter()創(chuàng)建一個(gè)包含給定數(shù)組的每個(gè)第 n 個(gè)元素的新數(shù)組。
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === 0); // everyNth([1,2,3,4,5,6], 2) -> [ 1, 3, 5 ]
? 返回頂部
filterNonUnique篩選出數(shù)組中的非唯一值。
對(duì)于只包含唯一值的數(shù)組, 請(qǐng)使用Array.filter()。
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); // filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]
? 返回頂部
flatten拼合數(shù)組。
使用Array.reduce()獲取數(shù)組中的所有元素和concat()以拼合它們。
const flatten = arr => arr.reduce((a, v) => a.concat(v), []); // flatten([1,[2],3,4]) -> [1,2,3,4]
? 返回頂部
flattenDepth將數(shù)組向上拼合到指定深度。
使用遞歸, 遞減depth, 每層深度為1。使用Array.reduce()和Array.concat()來(lái)合并元素或數(shù)組?;厩闆r下, 對(duì)于等于1的depth停止遞歸。省略第二個(gè)元素,depth僅拼合到1的深度 (單個(gè)拼合)。
const flattenDepth = (arr, depth = 1) => depth != 1 ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flattenDepth(v, depth - 1) : v), []) : arr.reduce((a, v) => a.concat(v), []); // flattenDepth([1,[2],[[[3],4],5]], 2) -> [1,2,[3],4,5]
? 返回頂部
groupby根據(jù)給定函數(shù)對(duì)數(shù)組元素進(jìn)行分組。
使用Array.map()將數(shù)組的值映射到函數(shù)或?qū)傩悦J褂?b>Array.reduce()創(chuàng)建一個(gè)對(duì)象, 其中的鍵是從映射的結(jié)果生成的。
const groupBy = (arr, func) => arr.map(typeof func === "function" ? func : val => val[func]) .reduce((acc, val, i) => { acc[val] = (acc[val] || []).concat(arr[i]); return acc; }, {}); // groupBy([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]} // groupBy(["one", "two", "three"], "length") -> {3: ["one", "two"], 5: ["three"]}
? 返回頂部
head返回列表的頭。
使用arr[0]可返回傳遞的數(shù)組的第一個(gè)元素。
const head = arr => arr[0]; // head([1,2,3]) -> 1
? 返回頂部
initial返回除最后一個(gè)數(shù)組之外的所有元素。
使用 "arr.slice(0,-1)" 返回?cái)?shù)組的最后一個(gè)元素。
const initial = arr => arr.slice(0, -1); // initial([1,2,3]) -> [1,2]
? 返回頂部
initializeArrayWithRange初始化包含指定范圍內(nèi)的數(shù)字的數(shù)組。
使用Array(end-start)創(chuàng)建所需長(zhǎng)度的數(shù)組Array.map()以填充區(qū)域中所需的值??梢允÷?b>start以使用默認(rèn)值0.
const initializeArrayWithRange = (end, start = 0) => Array.from({ length: end - start }).map((v, i) => i + start); // initializeArrayWithRange(5) -> [0,1,2,3,4]
? 返回頂部
initializeArrayWithValues初始化并填充具有指定值的數(shù)組。
使用Array(n)創(chuàng)建所需長(zhǎng)度的數(shù)組,fill(v)以填充所需的值??梢允÷?b>value以使用默認(rèn)值0.
const initializeArrayWithValues = (n, value = 0) => Array(n).fill(value); // initializeArrayWithValues(5, 2) -> [2,2,2,2,2]
? 返回頂部
intersection返回兩個(gè)數(shù)組中存在的元素的列表。
從b創(chuàng)建Set, 然后使用Array.filter()on a只保留b中包含的值.
const intersection = (a, b) => { const s = new Set(b); return a.filter(x => s.has(x)); }; // intersection([1,2,3], [4,3,2]) -> [2,3]
? 返回頂部
last返回?cái)?shù)組中的最后一個(gè)元素。
使用arr.length - 1可計(jì)算給定數(shù)組的最后一個(gè)元素的索引并返回它。
const last = arr => arr[arr.length - 1]; // last([1,2,3]) -> 3
? 返回頂部
mapObject使用函數(shù)將數(shù)組的值映射到對(duì)象, 其中鍵值對(duì)由原始值作為鍵和映射值組成。
使用匿名內(nèi)部函數(shù)范圍來(lái)聲明未定義的內(nèi)存空間, 使用閉包來(lái)存儲(chǔ)返回值。使用新的Array可將該數(shù)組與函數(shù)的映射放在其數(shù)據(jù)集上, 而逗號(hào)運(yùn)算符返回第二個(gè)步驟, 而不需要從一個(gè)上下文移動(dòng)到另一個(gè)環(huán)境 (由于關(guān)閉和操作順序)。
const mapObject = (arr, fn) => (a => (a = [arr, arr.map(fn)], a[0].reduce( (acc,val,ind) => (acc[val] = a[1][ind], acc), {}) )) ( ); /* const squareIt = arr => mapObject(arr, a => a*a) squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 } */
? 返回頂部
nthElement返回?cái)?shù)組的第 n 個(gè)元素。
使用Array.slice()可獲取包含第 n 個(gè)元素的數(shù)組。如果索引超出界限, 則返回[]。省略第二個(gè)參數(shù)n, 以獲取數(shù)組的第一個(gè)元素。
const nthElement = (arr, n=0) => (n>0? arr.slice(n,n+1) : arr.slice(n))[0]; // nthElement(["a","b","c"],1) -> "b" // nthElement(["a","b","b"],-3) -> "a"
? 返回頂部
pick從對(duì)象中選取對(duì)應(yīng)于給定鍵的鍵值對(duì)。
使用Array.reduce()將篩選/選取的密鑰轉(zhuǎn)換回具有相應(yīng)鍵值對(duì)的對(duì)象 (如果在 obj 中存在該鍵)。
const pick = (obj, arr) => arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); // pick({ "a": 1, "b": "2", "c": 3 }, ["a", "c"]) -> { "a": 1, "c": 3 }
? 返回頂部
pull對(duì)原始數(shù)組進(jìn)行變異, 以篩選出指定的值。
使用Array.filter()和Array.includes()來(lái)拉出不需要的值。使用Array.length = 0可將傳入的數(shù)組中的長(zhǎng)度重置為零, 并將其設(shè)置為Array.push(), 以便僅使用所提取的值填充它。
const pull = (arr, ...args) => { let pulled = arr.filter((v, i) => !args.includes(v)); arr.length = 0; pulled.forEach(v => arr.push(v)); }; // let myArray = ["a", "b", "c", "a", "b", "c"]; // pull(myArray, "a", "c"); // console.log(myArray) -> [ "b", "b" ]
? 返回頂部
remove從數(shù)組中移除給定函數(shù)返回false的元素.
使用Array.filter()查找返回 truthy 值的數(shù)組元素和Array.reduce()以使用Array.splice()刪除元素。使用三參數(shù) (func value, index, array調(diào)用函數(shù)).
const remove = (arr, func) => Array.isArray(arr) ? arr.filter(func).reduce((acc, val) => { arr.splice(arr.indexOf(val), 1); return acc.concat(val); }, []) : []; // remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]
? 返回頂部
sample返回?cái)?shù)組中的隨機(jī)元素。
使用Math.random()生成一個(gè)隨機(jī)數(shù), 將它與length相乘, 并使用數(shù)學(xué)將其舍入到最接近的整數(shù)Math.floor()。此方法也適用于字符串。
const sample = arr => arr[Math.floor(Math.random() * arr.length)]; // sample([3, 7, 9, 11]) -> 9
? 返回頂部
shuffle隨機(jī)數(shù)組值的順序。
使用Array.sort()可在比較器中使用Math.random()重新排序元素。
const shuffle = arr => arr.sort(() => Math.random() - 0.5); // shuffle([1,2,3]) -> [2,3,1]
? 返回頂部
similarity返回兩個(gè)數(shù)組中都顯示的元素的數(shù)組。
使用filter()可刪除不屬于values的值, 使用includes()確定.
const similarity = (arr, values) => arr.filter(v => values.includes(v)); // similarity([1,2,3], [1,2,4]) -> [1,2]
? 返回頂部
symmetricDifference返回兩個(gè)數(shù)組之間的對(duì)稱差。
從每個(gè)數(shù)組創(chuàng)建一個(gè)Set, 然后對(duì)它們中的每一個(gè)都使用Array.filter(), 以便只保留其他值中不包含的數(shù)值。
const symmetricDifference = (a, b) => { const sA = new Set(a), sB = new Set(b); return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; } // symmetricDifference([1,2,3], [1,2,4]) -> [3,4]
? 返回頂部
tail返回?cái)?shù)組中的所有元素, 除第一個(gè)。
如果數(shù)組的length大于1, 則返回arr.slice(1), 否則返回整個(gè)數(shù)組。
const tail = arr => arr.length > 1 ? arr.slice(1) : arr; // tail([1,2,3]) -> [2,3] // tail([1]) -> [1]
? 返回頂部
take返回一個(gè)數(shù)組, 其中 n 個(gè)元素從開(kāi)始處移除。
使用Array.slice()創(chuàng)建數(shù)組的切片, 其中包含從開(kāi)始處取出的n元素。
const take = (arr, n = 1) => arr.slice(0, n); // take([1, 2, 3], 5) -> [1, 2, 3] // take([1, 2, 3], 0) -> []
? 返回頂部
takeRight返回一個(gè)數(shù)組, 其中 n 個(gè)元素從末尾移除。
使用Array.slice()創(chuàng)建數(shù)組的切片, 其中包含從末尾取出的n元素。
const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); // takeRight([1, 2, 3], 2) -> [ 2, 3 ] // takeRight([1, 2, 3]) -> [3]
? 返回頂部
union返回在兩個(gè)數(shù)組中的任意一個(gè)中存在的每個(gè)元素。
創(chuàng)建一個(gè)Set, 其中包含a和b的所有值, 并將其轉(zhuǎn)換為數(shù)組。
const union = (a, b) => Array.from(new Set([...a, ...b])); // union([1,2,3], [4,3,2]) -> [1,2,3,4]
? 返回頂部
without篩選出數(shù)組中具有指定值之一的元素。
使用Array.filter()創(chuàng)建不包括的數(shù)組 (使用!Array.includes()) 所有給定值。
const without = (arr, ...args) => arr.filter(v => !args.includes(v)); // without([2, 1, 2, 3], 1, 2) -> [3]
? 返回頂部
zip創(chuàng)建基于原始數(shù)組中的位置分組的元素?cái)?shù)組。
使用Math.max.apply()獲取參數(shù)中最長(zhǎng)的數(shù)組。創(chuàng)建一個(gè)以該長(zhǎng)度為返回值的數(shù)組, 并使用 map 函數(shù)創(chuàng)建一個(gè)分組元素的數(shù)組Array.from()如果參數(shù)數(shù)組的長(zhǎng)度不同, 則在未找到任何值的情況下使用undefined。
const zip = (...arrays) => { const maxLength = Math.max(...arrays.map(x => x.length)); return Array.from({length: maxLength}).map((_, i) => { return Array.from({length: arrays.length}, (_, k) => arrays[k][i]); }) } //zip(["a", "b"], [1, 2], [true, false]); -> [["a", 1, true], ["b", 2, false]] //zip(["a"], [1, 2], [true, false]); -> [["a", 1, true], [undefined, 2, false]]瀏覽器
? 返回頂部
bottomVisible如果頁(yè)的底部可見(jiàn), 則返回true, 否則為false。
使用scrollY、scrollHeight和clientHeight來(lái)確定頁(yè)面底部是否可見(jiàn)。
const bottomVisible = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight || document.documentElement.clientHeight; // bottomVisible() -> true
? 返回頂部
currentURL返回當(dāng)前 URL。
使用window.location.href獲取當(dāng)前 URL。
const currentURL = () => window.location.href; // currentUrl() -> "https://google.com"
? 返回頂部
elementIsVisibleInViewport如果指定的元素在視區(qū)中可見(jiàn), 則返回true, 否則為false。
使用Element.getBoundingClientRect()和window.inner(Width|Height)值以確定給定元素在視區(qū)中是否可見(jiàn)。省略第二個(gè)參數(shù)以確定該元素是否完全可見(jiàn), 或指定true以確定它是否部分可見(jiàn)。
const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; // e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10} // elementIsVisibleInViewport(el) -> false (not fully visible) // elementIsVisibleInViewport(el, true) -> true (partially visible)
? 返回頂部
getScrollPosition返回當(dāng)前頁(yè)的滾動(dòng)位置。
如果已定義, 則使用pageXOffset和pageYOffset, 否則scrollLeft和scrollTop??梢允÷?b>el以使用window的默認(rèn)值.
const getScrollPosition = (el = window) => ({x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft, y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop}); // getScrollPosition() -> {x: 0, y: 200}
? 返回頂部
getURLParameters返回一個(gè)包含當(dāng)前 URL 參數(shù)的對(duì)象。
使用match()與適當(dāng)?shù)恼齽t表達(dá)式來(lái)獲取所有鍵值對(duì),Array.reduce()可將它們映射并合并到單個(gè)對(duì)象中。將location.search作為要應(yīng)用于當(dāng)前url的參數(shù)傳遞.
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"}
? 返回頂部
redirect重定向到指定的 URL。
使用window.location.href或window.location.replace()重定向到url。傳遞第二個(gè)參數(shù)以模擬鏈接單擊 (true-默認(rèn)值) 或 HTTP 重定向 (false).
const redirect = (url, asLink = true) => asLink ? window.location.href = url : window.location.replace(url); // redirect("https://google.com")
? 返回頂部
scrollToTop平滑滾動(dòng)到頁(yè)面頂部。
使用document.documentElement.scrollTop或document.body.scrollTop從頂部獲取距離。從頂部的距離的一小部分滾動(dòng)。使用window.requestAnimationFrame()對(duì)滾動(dòng)進(jìn)行動(dòng)畫處理。
const scrollToTop = () => { const c = document.documentElement.scrollTop || document.body.scrollTop; if (c > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, c - c / 8); } }; // scrollToTop()日期
? 返回頂部
getDaysDiffBetweenDates返回兩個(gè)日期之間的差異 (以天為值)。
計(jì)算Date對(duì)象之間的差異 (以天為)。
const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); // getDaysDiffBetweenDates(new Date("2017-12-13"), new Date("2017-12-22")) -> 9
? 返回頂部
JSONToDate將 JSON 對(duì)象轉(zhuǎn)換為日期。
使用Date(), 將 JSON 格式的日期轉(zhuǎn)換為可讀格式 (dd/mm/yyyy日)).
const JSONToDate = arr => { const dt = new Date(parseInt(arr.toString().substr(6))); return `${ dt.getDate() }/${ dt.getMonth() + 1 }/${ dt.getFullYear() }` }; // JSONToDate(/Date(1489525200000)/) -> "14/3/2017"
? 返回頂部
toEnglishDate將日期從美國(guó)格式轉(zhuǎn)換為英文格式。
使用Date.toISOString()、split("T")和replace()將日期從美式格式轉(zhuǎn)換為英文格式。如果傳遞的時(shí)間不能轉(zhuǎn)換為日期, 則拋出錯(cuò)誤。
const toEnglishDate = (time) => {try{return new Date(time).toISOString().split("T")[0].replace(/-/g, "/")}catch(e){return}}; // toEnglishDate("09/21/2010") -> "21/09/2010"函數(shù)類
? 返回頂部
chainAsync鏈異步函數(shù)。
循環(huán)遍歷包含異步事件的函數(shù)數(shù)組, 當(dāng)每個(gè)異步事件完成時(shí)調(diào)用next。
const chainAsync = fns => { let curr = 0; const next = () => fns[curr++](next); next(); }; /* chainAsync([ next => { console.log("0 seconds"); setTimeout(next, 1000); }, next => { console.log("1 second"); setTimeout(next, 1000); }, next => { console.log("2 seconds"); } ]) */
? 返回頂部
compose執(zhí)行從右向左的函數(shù)組合。
使用Array.reduce()執(zhí)行從右向左的函數(shù)組合。最后一個(gè) (最右邊) 的函數(shù)可以接受一個(gè)或多個(gè)參數(shù);其余的函數(shù)必須是一元的。
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); /* const add5 = x => x + 5 const multiply = (x, y) => x * y const multiplyAndAdd5 = compose(add5, multiply) multiplyAndAdd5(5, 2) -> 15 */
? 返回頂部
curryCurries a function.
使用遞歸。如果提供的參數(shù) (變量) 的數(shù)量足夠, 請(qǐng)調(diào)用傳遞的函數(shù)args f。否則, 返回需要其余參數(shù)的擴(kuò)充函數(shù)f。如果你想咖喱一個(gè)函數(shù), 接受可變數(shù)目的參數(shù) (如Math.min()), 可以選擇將參數(shù)的個(gè)數(shù)傳遞到第二個(gè)參數(shù)arity(可變函數(shù)).
const curry = (fn, arity = fn.length, ...args) => arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); // curry(Math.pow)(2)(10) -> 1024 // curry(Math.min, 3)(10)(50)(2) -> 2
? 返回頂部
functionName記錄函數(shù)的名稱。
使用console.debug()和傳遞的方法的name屬性將方法的名稱記錄到控制臺(tái)的debug通道中。
const functionName = fn => (console.debug(fn.name), fn); // functionName(Math.max) -> max (logged in debug channel of console)
? 返回頂部
pipe執(zhí)行從左向右的函數(shù)組合。
使用Array.reduce()與擴(kuò)展運(yùn)算符 (...) 執(zhí)行從左向右的函數(shù)組合。第一個(gè) (最左邊的) 函數(shù)可以接受一個(gè)或多個(gè)參數(shù);其余的函數(shù)必須是一元的。
const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); /* const add5 = x => x + 5 const multiply = (x, y) => x * y const multiplyAndAdd5 = pipeFunctions(multiply, add5) multiplyAndAdd5(5, 2) -> 15 */
? 返回頂部
promisify轉(zhuǎn)換異步函數(shù)以返回一個(gè)承諾。
使用討好返回一個(gè)返回調(diào)用原始函數(shù)的Promise的函數(shù)。使用...rest運(yùn)算符傳入所有參數(shù)。
在節(jié)點(diǎn) 8 + 中, 可以使用 util.promisify
const promisify = func => (...args) => new Promise((resolve, reject) => func(...args, (err, result) => err ? reject(err) : resolve(result)) ); // const delay = promisify((d, cb) => setTimeout(cb, d)) // delay(2000).then(() => console.log("Hi!")) -> Promise resolves after 2s
? 返回頂部
runPromisesInSeries運(yùn)行一系列的承諾系列。
使用Array.reduce()創(chuàng)建一個(gè)承諾鏈, 每個(gè)承諾在解決時(shí)返回下一個(gè)承諾。
const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); // const delay = (d) => new Promise(r => setTimeout(r, d)) // runPromisesInSeries([() => delay(1000), () => delay(2000)]) -> executes each promise sequentially, taking a total of 3 seconds to complete
? 返回頂部
sleep延遲異步函數(shù)的執(zhí)行。
延遲執(zhí)行async函數(shù)的一部分, 將其放入休眠狀態(tài), 返回Promise.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); /* async function sleepyWork() { console.log("I"m going to sleep for 1 second."); await sleep(1000); console.log("I woke up after 1 second."); } */數(shù)學(xué)
? 返回頂部
arrayAverage返回?cái)?shù)字?jǐn)?shù)組的平均值。
使用Array.reduce()將每個(gè)值添加到累加器中, 并以0的值初始化, 除以數(shù)組的length。
const arrayAverage = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length; // arrayAverage([1,2,3]) -> 2
? 返回頂部
arraySum返回一個(gè)數(shù)字?jǐn)?shù)組的總和。
使用Array.reduce()將每個(gè)值添加到累加器中, 并以0值初始化.
const arraySum = arr => arr.reduce((acc, val) => acc + val, 0); // arraySum([1,2,3,4]) -> 10
? 返回頂部
collatz應(yīng)用 Collatz 算法。
如果n是偶數(shù), 則返回n/2。否則返回3n+1.
const collatz = n => (n % 2 == 0) ? (n / 2) : (3 * n + 1); // collatz(8) --> 4 // collatz(5) --> 16
? 返回頂部
collatz將數(shù)字轉(zhuǎn)換為數(shù)字?jǐn)?shù)組。
將數(shù)字轉(zhuǎn)換為字符串, 在 ES6 ([...string]) 中使用擴(kuò)展運(yùn)算符生成數(shù)組。使用Array.map()和parseInt()將每個(gè)值轉(zhuǎn)換為整數(shù)。
const digitize = n => [...""+n].map(i => parseInt(i)); // digitize(2334) -> [2, 3, 3, 4]
? 返回頂部
digitize返回兩點(diǎn)之間的距離。
使用Math.hypot()計(jì)算兩個(gè)點(diǎn)之間的歐氏距離。
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); // distance(1,1, 2,3) -> 2.23606797749979
? 返回頂部
distance計(jì)算數(shù)字的階乘。
使用遞歸。如果n小于或等于1, 則返回1。否則, 返回n的乘積和n - 1的階乘。如果n為負(fù)數(shù), 則引發(fā)異常。
const factorial = n => n < 0 ? (() => { throw new TypeError("Negative numbers are not allowed!") })() : n <= 1 ? 1 : n * factorial(n - 1); // factorial(6) -> 720
? 返回頂部
fibonacci生成一個(gè)數(shù)組, 包含斐波那契數(shù)列, 直到第 n 個(gè)項(xiàng)。
創(chuàng)建一個(gè)指定長(zhǎng)度的空數(shù)組, 初始化前兩個(gè)值 (0和1)。使用Array.reduce()可將值添加到數(shù)組中, 方法是使用前兩個(gè)值的總和, 但前兩個(gè)數(shù)值除外。
const fibonacci = n => Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), []); // fibonacci(5) -> [0,1,1,2,3]
? 返回頂部
gcd計(jì)算兩個(gè)數(shù)字之間最大的公共除數(shù)。
使用遞歸?;厩闆r是當(dāng)y等于0時(shí)。在這種情況下, 返回x。否則, 返回y的 GCD 和除法的其余部分x/y.
const gcd = (x, y) => !y ? x : gcd(y, x % y); // gcd (8, 36) -> 4
? 返回頂部
hammingDistance計(jì)算兩個(gè)值之間的漢明距離。
使用 XOR 運(yùn)算符 (^) 可查找兩個(gè)數(shù)字之間的位差, 使用toString(2)轉(zhuǎn)換為二進(jìn)制字符串。使用match(/1/g)計(jì)算并返回字符串中1的數(shù)目。.
const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || "").length; // hammingDistance(2,3) -> 1
? 返回頂部
isDivisible檢查第一個(gè)數(shù)值參數(shù)是否可被另一個(gè)數(shù)字變量整除。
使用模數(shù)運(yùn)算符 (%) 檢查余數(shù)是否等于0.
const isDivisible = (dividend, divisor) => dividend % divisor === 0; // isDivisible(6,3) -> true
? 返回頂部
iseven如果給定的數(shù)字為偶數(shù), 則返回true, 否則為false。
檢查一個(gè)數(shù)字是奇數(shù)還是使用模數(shù) (%) 運(yùn)算符。如果數(shù)字為偶數(shù), 則返回true, 如果數(shù)字為奇數(shù), 則為false。
const isEven = num => num % 2 === 0; // isEven(3) -> false
? 返回頂部
lcm返回兩個(gè)數(shù)字中最不常見(jiàn)的倍數(shù)。
使用最大的公共除數(shù) (GCD) 公式和Math.abs()來(lái)確定最不常見(jiàn)的倍數(shù)。GCD 公式使用遞歸。
const lcm = (x,y) => { const gcd = (x, y) => !y ? x : gcd(y, x % y); return Math.abs(x*y)/(gcd(x,y)); }; // lcm(12,7) -> 84
? 返回頂部
median返回?cái)?shù)字?jǐn)?shù)組的中間值。
找到數(shù)組的中間, 使用Array.sort()來(lái)對(duì)值進(jìn)行排序。如果length為奇數(shù), 則返回中點(diǎn)的數(shù)字, 否則為兩個(gè)中間數(shù)的平均值。
const median = arr => { const mid = Math.floor(arr.length / 2), nums = arr.sort((a, b) => a - b); return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; }; // median([5,6,50,1,-5]) -> 5 // median([0,10,-2,7]) -> 3.5
? 返回頂部
palindrome如果給定字符串為回文, 則返回true, 否則為false。
轉(zhuǎn)換字符串toLowerCase()并使用replace()從其中刪除非字母數(shù)字字符。然后,split("")到各個(gè)字符,reverse(),join(""), 并將其與原始的、不可逆轉(zhuǎn)的字符串進(jìn)行比較, 然后將其轉(zhuǎn)換為tolowerCase().
const palindrome = str => { const s = str.toLowerCase().replace(/[W_]/g,""); return s === s.split("").reverse().join(""); } // palindrome("taco cat") -> true
? 返回頂部
percentile使用百分比公式計(jì)算給定數(shù)組中有多少個(gè)數(shù)小于或等于給定值。
使用Array.reduce()計(jì)算值的下面有多少, 有多少個(gè)數(shù)是相同的值, 并應(yīng)用百分比公式。
const percentile = (arr, val) => 100 * arr.reduce((acc,v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; // percentile([1,2,3,4,5,6,7,8,9,10], 6) -> 55
? 返回頂部
powerset返回給定數(shù)組的真子集。
使用Array.reduce()與Array.map()組合, 以循環(huán)訪問(wèn)元素并將其合并到包含所有組合的數(shù)組中。
const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); // powerset([1,2]) -> [[], [1], [2], [2,1]]
? 返回頂部
randomIntegerInRange返回指定范圍內(nèi)的隨機(jī)整數(shù)。
使用Math.random()生成一個(gè)隨機(jī)數(shù)并將其映射到所需的范圍, 使用Math.floor()使其成為整數(shù)。
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; // randomIntegerInRange(0, 5) -> 2
? 返回頂部
randomNumberInRange返回指定范圍內(nèi)的隨機(jī)數(shù)。
使用Math.random()生成隨機(jī)值, 并使用乘法將其映射到所需的范圍。
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; // randomNumberInRange(2,10) -> 6.0211363285087005
? 返回頂部
round將數(shù)字四舍五入到指定的位數(shù)。
使用Math.round()和模板文本將數(shù)字舍入到指定的位數(shù)。省略第二個(gè)參數(shù),decimals舍入為整數(shù)。
const round = (n, decimals=0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); // round(1.005, 2) -> 1.01
? 返回頂部
standardDeviation返回?cái)?shù)字?jǐn)?shù)組的標(biāo)準(zhǔn)偏差。
使用Array.reduce()計(jì)算值的平均值、方差和方差的總和, 值的方差, 然后確定標(biāo)準(zhǔn)偏差。可以省略第二個(gè)參數(shù)以獲取樣本標(biāo)準(zhǔn)偏差, 或?qū)⑵湓O(shè)置為true以獲取總體標(biāo)準(zhǔn)偏差。
const standardDeviation = (arr, usePopulation = false) => { const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; return Math.sqrt( arr.reduce((acc, val) => acc.concat(Math.pow(val - mean, 2)), []) .reduce((acc, val) => acc + val, 0) / (arr.length - (usePopulation ? 0 : 1)) ); }; // standardDeviation([10,2,38,23,38,23,21]) -> 13.284434142114991 (sample) // standardDeviation([10,2,38,23,38,23,21], true) -> 12.29899614287479 (population)媒體
? 返回頂部
speechSynthesis執(zhí)行語(yǔ)音合成 (實(shí)驗(yàn))。
使用SpeechSynthesisUtterance.voice和window.speechSynthesis.getVoices()將郵件轉(zhuǎn)換為語(yǔ)音。使用window.speechSynthesis.speak()播放該消息。了解有關(guān)Web 語(yǔ)音 API 的 SpeechSynthesisUtterance 接口的詳細(xì)信息.
const speechSynthesis = message => { const msg = new SpeechSynthesisUtterance(message); msg.voice = window.speechSynthesis.getVoices()[0]; window.speechSynthesis.speak(msg); }; // speechSynthesis("Hello, World") -> plays the message節(jié)點(diǎn)
? 返回頂部
JSONToFile將 JSON 對(duì)象寫入文件。
使用fs.writeFile()、模板文本和JSON.stringify()將json對(duì)象寫入.json文件。
const fs = require("fs"); const JSONToFile = (obj, filename) => fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)) // JSONToFile({test: "is passed"}, "testJsonFile") -> writes the object to "testJsonFile.json"
? 返回頂部
readFileLines返回指定文件中的行的數(shù)組。
在fs節(jié)點(diǎn)包中使用readFileSync函數(shù)可以從文件創(chuàng)建Buffer。使用toString(encoding)函數(shù)將緩沖區(qū)轉(zhuǎn)換為字符串。通過(guò)spliting 文件內(nèi)容行從文件內(nèi)容創(chuàng)建數(shù)組 (每個(gè) ).
const fs = require("fs"); const readFileLines = filename => fs.readFileSync(filename).toString("UTF8").split(" "); /* contents of test.txt : line1 line2 line3 ___________________________ let arr = readFileLines("test.txt") console.log(arr) // -> ["line1", "line2", "line3"] */對(duì)象
? 返回頂部
cleanObj移除從 JSON 對(duì)象指定的屬性之外的任何特性。
使用Object.keys()方法可以遍歷給定的 json 對(duì)象并刪除在給定數(shù)組中不是included 的鍵。另外, 如果給它一個(gè)特殊的鍵 (childIndicator), 它將在里面深入搜索, 并將函數(shù)應(yīng)用于內(nèi)部對(duì)象。
const cleanObj = (obj, keysToKeep = [], childIndicator) => { Object.keys(obj).forEach(key => { if (key === childIndicator) { cleanObj(obj[key], keysToKeep, childIndicator); } else if (!keysToKeep.includes(key)) { delete obj[key]; } }) } /* const testObj = {a: 1, b: 2, children: {a: 1, b: 2}} cleanObj(testObj, ["a"],"children") console.log(testObj)// { a: 1, children : { a: 1}} */
? 返回頂部
objectFromPairs從給定的鍵值對(duì)創(chuàng)建對(duì)象。
使用Array.reduce()創(chuàng)建和組合鍵值對(duì)。
const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {}); // objectFromPairs([["a",1],["b",2]]) -> {a: 1, b: 2}
? 返回頂部
objectToPairs從對(duì)象創(chuàng)建鍵值對(duì)數(shù)組的數(shù)組。
使用Object.keys()和Array.map()循環(huán)訪問(wèn)對(duì)象的鍵并生成具有鍵值對(duì)的數(shù)組。
const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); // objectToPairs({a: 1, b: 2}) -> [["a",1],["b",2]])
? 返回頂部
shallowClone創(chuàng)建對(duì)象的淺表克隆。
使用Object.assign()和一個(gè)空對(duì)象 ({}) 創(chuàng)建原始的淺克隆。
const shallowClone = obj => Object.assign({}, obj); /* const a = { x: true, y: 1 }; const b = shallowClone(a); a === b -> false */
? 返回頂部
truthCheckCollection檢查謂詞 (第二個(gè)參數(shù)) 是否 truthy 集合的所有元素 (第一個(gè)參數(shù))。
使用Array.every()檢查每個(gè)傳遞的對(duì)象是否具有指定的屬性, 以及是否返回 truthy 值。
truthCheckCollection = (collection, pre) => (collection.every(obj => obj[pre])); // truthCheckCollection([{"user": "Tinky-Winky", "sex": "male"}, {"user": "Dipsy", "sex": "male"}], "sex") -> true字符串
? 返回頂部
anagrams生成字符串的所有字謎 (包含重復(fù)項(xiàng))。
使用遞歸。對(duì)于給定字符串中的每個(gè)字母, 為其其余字母創(chuàng)建所有部分字謎。使用Array.map()將字母與每個(gè)部分變位詞組合在一起, 然后將Array.reduce()組合在一個(gè)數(shù)組中的所有字謎?;厩闆r為字符串length等于2或1.
const anagrams = str => { if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; return str.split("").reduce((acc, letter, i) => acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []); }; // anagrams("abc") -> ["abc","acb","bac","bca","cab","cba"]
? 返回頂部
Capitalize將字符串的第一個(gè)字母大寫。
使用 destructuring 和toUpperCase()可將第一個(gè)字母、...rest用于獲取第一個(gè)字母之后的字符數(shù)組, 然后是Array.join("")以使其成為字符串。省略lowerRest參數(shù)以保持字符串的其余部分不變, 或?qū)⑵湓O(shè)置為true以轉(zhuǎn)換為小寫。
const capitalize = ([first,...rest], lowerRest = false) => first.toUpperCase() + (lowerRest ? rest.join("").toLowerCase() : rest.join("")); // capitalize("myName") -> "MyName" // capitalize("myName", true) -> "Myname"
? 返回頂部
capitalizeEveryWord將字符串中每個(gè)單詞的首字母大寫。
使用replace()匹配每個(gè)單詞和toUpperCase()的第一個(gè)字符以將其大寫。
const capitalizeEveryWord = str => str.replace(/[a-z]/g, char => char.toUpperCase()); // capitalizeEveryWord("hello world!") -> "Hello World!"
? 返回頂部
escapeRegExp轉(zhuǎn)義要在正則表達(dá)式中使用的字符串。
使用replace()可轉(zhuǎn)義特殊字符。
const escapeRegExp = str => str.replace(/[.*+?^${}()|[]]/g, "$&"); // escapeRegExp("(test)") -> (test)
? 返回頂部
fromCamelCase從匹配轉(zhuǎn)換字符串。
使用replace()可刪除下劃線、連字符和空格, 并將單詞轉(zhuǎn)換為匹配。省略第二個(gè)參數(shù)以使用默認(rèn)分隔符_.
const fromCamelCase = (str, separator = "_") => str.replace(/([a-zd])([A-Z])/g, "$1" + separator + "$2") .replace(/([A-Z]+)([A-Z][a-zd]+)/g, "$1" + separator + "$2").toLowerCase(); // fromCamelCase("someDatabaseFieldName", " ") -> "some database field name" // fromCamelCase("someLabelThatNeedsToBeCamelized", "-") -> "some-label-that-needs-to-be-camelized" // fromCamelCase("someJavascriptProperty", "_") -> "some_javascript_property"
? 返回頂部
reverseString反轉(zhuǎn)字符串。
使用數(shù)組 destructuring 和Array.reverse()可反轉(zhuǎn)字符串中字符的順序。使用join("")組合字符以獲取字符串.
const reverseString = str => [...str].reverse().join(""); // reverseString("foobar") -> "raboof"
? 返回頂部
sortCharactersInString按字母順序?qū)ψ址械淖址M(jìn)行排序。
使用split("")、Array.sort()利用localeCompare()重新組合使用join("").
const sortCharactersInString = str => str.split("").sort((a, b) => a.localeCompare(b)).join(""); // sortCharactersInString("cabbage") -> "aabbceg"
? 返回頂部
toCamelCase將字符串轉(zhuǎn)換為匹配。
使用replace()可刪除下劃線、連字符和空格, 并將單詞轉(zhuǎn)換為匹配。
const toCamelCase = str => str.replace(/^([A-Z])|[s-_]+(w)/g, (match, p1, p2, offset) => p2 ? p2.toUpperCase() : p1.toLowerCase()); // toCamelCase("some_database_field_name") -> "someDatabaseFieldName" // toCamelCase("Some label that needs to be camelized") -> "someLabelThatNeedsToBeCamelized" // toCamelCase("some-javascript-property") -> "someJavascriptProperty" // toCamelCase("some-mixed_string with spaces_underscores-and-hyphens") -> "someMixedStringWithSpacesUnderscoresAndHyphens"
? 返回頂部
truncateString將字符串截?cái)酁橹付ㄩL(zhǎng)度。
確定字符串的length是否大于num。將截?cái)嗟淖址祷氐剿璧拈L(zhǎng)度, 并將...追加到末尾或原始字符串。
const truncateString = (str, num) => str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + "..." : str; // truncateString("boomerang", 7) -> "boom..."實(shí)用
? 返回頂部
coalesce返回第一個(gè)非空/未定義參數(shù)。
使用Array.find()返回第一個(gè)非null/undefined的參數(shù)。
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)) // coalesce(null,undefined,"",NaN, "Waldo") -> ""
? 返回頂部
coalesceFactory返回自定義的聯(lián)合函數(shù), 返回從提供的參數(shù)驗(yàn)證函數(shù)返回true的第一個(gè)參數(shù)。
使用Array.find()返回從提供的參數(shù)驗(yàn)證函數(shù)返回true的第一個(gè)參數(shù)。
const coalesceFactory = valid => (...args) => args.find(valid); // const customCoalesce = coalesceFactory(_ => ![null, undefined, "", NaN].includes(_)) // customCoalesce(undefined, null, NaN, "", "Waldo") //-> "Waldo"
? 返回頂部
extendHex將3位色碼擴(kuò)展為6位色碼。
使用Array.map()、split()和Array.join()來(lái)加入映射數(shù)組, 將3位的 RGB notated 十六進(jìn)制 color-code 轉(zhuǎn)換為6位數(shù)字形式。Array.slice()用于從字符串啟動(dòng)中刪除#, 因?yàn)樗砑恿艘淮巍?/p>
const extendHex = shortHex => "#" + shortHex.slice(shortHex.startsWith("#") ? 1 : 0).split("").map(x => x+x).join("") // extendHex("#03f") -> "#0033ff" // extendHex("05a") -> "#0055aa"
? 返回頂部
gettype返回值的本機(jī)類型。
如果值未定義或?yàn)?null, 則返回小寫的構(gòu)造函數(shù)名稱、"未定義" 或 "null"
const getType = v => v === undefined ? "undefined" : v === null ? "null" : v.constructor.name.toLowerCase(); // getType(new Set([1,2,3])) -> "set"
? 返回頂部
hexToRGB將 colorcode 轉(zhuǎn)換為rgb()字符串。
使用按位右運(yùn)算符和掩碼位與&(and) 運(yùn)算符將十六進(jìn)制顏色代碼 (前綴為#) 轉(zhuǎn)換為具有 RGB 值的字符串。如果它是一個(gè)3位數(shù)的 colorcode, 那么用 extendHex () 函數(shù) (ref.extendHex代碼段) 擴(kuò)展的6位 colorcode 進(jìn)行相同的處理
const hexToRgb = hex => { const extendHex = shortHex => "#" + shortHex.slice(shortHex.startsWith("#") ? 1 : 0).split("").map(x => x+x).join(""); const extendedHex = hex.slice(hex.startsWith("#") ? 1 : 0).length === 3 ? extendHex(hex) : hex; return `rgb(${parseInt(extendedHex.slice(1), 16) >> 16}, ${(parseInt(extendedHex.slice(1), 16) & 0x00ff00) >> 8}, ${parseInt(extendedHex.slice(1), 16) & 0x0000ff})`; } // hexToRgb("#27ae60") -> "rgb(39, 174, 96)" // hexToRgb("#acd") -> "rgb(170, 204, 221)"
? 返回頂部
isArray檢查給定參數(shù)是否為數(shù)組。
使用Array.isArray()檢查某個(gè)值是否屬于數(shù)組。
const isArray = val => !!val && Array.isArray(val); // isArray(null) -> false // isArray([1]) -> true
? 返回頂部
isBoolean檢查給定的參數(shù)是否為本機(jī)布爾元素。
使用typeof檢查某個(gè)值是否被歸類為布爾基元。
const isBoolean = val => typeof val === "boolean"; // isBoolean(null) -> false // isBoolean(false) -> true
? 返回頂部
isFunction檢查給定參數(shù)是否為函數(shù)。
使用typeof檢查某個(gè)值是否被歸類為函數(shù)基元。
const isFunction = val => val && typeof val === "function"; // isFunction("x") -> false // isFunction(x => x) -> true
? 返回頂部
isNumber檢查給定參數(shù)是否為數(shù)字。
使用typeof檢查某個(gè)值是否歸類為數(shù)字基元。
const isNumber = val => typeof val === "number"; // isNumber("1") -> false // isNumber(1) -> true
? 返回頂部
isString檢查給定參數(shù)是否為字符串。
使用typeof檢查某個(gè)值是否屬于字符串基元。
const isString = val => typeof val === "string"; // isString(10) -> false // isString("10") -> true
? 返回頂部
isSymbol檢查給定參數(shù)是否為符號(hào)。
使用typeof檢查某個(gè)值是否被歸類為符號(hào)基元。
const isSymbol = val => typeof val === "symbol"; // isSymbol("x") -> false // isSymbol(Symbol("x")) -> true
? 返回頂部
RGBToHex將 RGB 組件的值轉(zhuǎn)換為 colorcode。
使用按位左移位運(yùn)算符 (<<) 和toString(16)將給定的 RGB 參數(shù)轉(zhuǎn)換為十六進(jìn)制字符串, 然后padStart(6,"0")以獲取6位十六進(jìn)制值。
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, "0"); // RGBToHex(255, 165, 1) -> "ffa501"
? 返回頂部
timeTaken測(cè)量執(zhí)行函數(shù)所用的時(shí)間。
使用console.time()和console.timeEnd()來(lái)測(cè)量開(kāi)始和結(jié)束時(shí)間之間的差異, 以確定回調(diào)執(zhí)行所用的時(shí)間。
const timeTaken = callback => { console.time("timeTaken"); const r = callback(); console.timeEnd("timeTaken"); return r; }; // timeTaken(() => Math.pow(2, 10)) -> 1024 // (logged): timeTaken: 0.02099609375ms
? 返回頂部
toOrdinalSuffix將序號(hào)后綴添加到數(shù)字。
使用模數(shù)運(yùn)算符 (%) 查找單個(gè)和十位數(shù)字的值。查找匹配的序號(hào)模式數(shù)字。如果在青少年模式中發(fā)現(xiàn)數(shù)字, 請(qǐng)使用青少年序號(hào)。
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"
? 返回頂部
UUIDGenerator生成 UUID。
使用cryptoAPI 生成 UUID, 符合RFC4122版本4。
const UUIDGenerator = () => ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16) ); // UUIDGenerator() -> "7982fcfe-5721-4632-bede-6000885be57d"
? 返回頂部
validateEmail如果給定的字符串是有效的電子郵件, 則返回true, 否則為false。
使用正則表達(dá)式檢查電子郵件是否有效。如果電子郵件有效, 則返回 true, 如果沒(méi)有, 則返回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(mymail@gmail.com) -> true
? 返回頂部
validateNumber如果給定值為數(shù)字, 則返回true, 否則為false。
將!isNaN與parseFloat()結(jié)合使用, 以檢查參數(shù)是否為數(shù)字。使用isFinite()檢查數(shù)字是否是有限的。使用Number()檢查強(qiáng)制是否保持。
const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; // validateNumber("10") -> truePowered by ? dragonir 2017
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.hztianpu.com/yun/90362.html
摘要:收藏優(yōu)秀組件庫(kù)合集前端掘金開(kāi)源的優(yōu)秀組件庫(kù)合集教你如何在應(yīng)用程序中使用本地文件上傳圖片前端掘金使用在中添加到的,現(xiàn)在可以讓內(nèi)容要求用戶選擇本地文件,然后讀取這些文件的內(nèi)容。 『收藏』VUE 優(yōu)秀 UI 組件庫(kù)合集 - 前端 - 掘金github 開(kāi)源的 Vue 優(yōu)秀 UI 組件庫(kù)合集?... 教你如何在 web 應(yīng)用程序中使用本地文件?上傳圖片file? - 前端 - 掘金使用在HTM...
摘要:收集的一些前端面試題從面試題發(fā)現(xiàn)不足,進(jìn)而查漏補(bǔ)缺,比通過(guò)面試更難得及各大互聯(lián)網(wǎng)公司前端筆試面試題篇及各大互聯(lián)網(wǎng)公司前端筆試面試題篇面試題個(gè)和個(gè)經(jīng)典面試題前端開(kāi)發(fā)面試題如何面試前端工程師很重要個(gè)變態(tài)題解析如何通過(guò)餓了么面試輕 收集的一些前端面試題 從面試題發(fā)現(xiàn)不足,進(jìn)而查漏補(bǔ)缺,比通過(guò)面試更難得 1 BAT及各大互聯(lián)網(wǎng)公司2014前端筆試面試題--Html,Css篇 2 BAT...
摘要:收集的一些前端面試題從面試題發(fā)現(xiàn)不足,進(jìn)而查漏補(bǔ)缺,比通過(guò)面試更難得及各大互聯(lián)網(wǎng)公司前端筆試面試題篇及各大互聯(lián)網(wǎng)公司前端筆試面試題篇面試題個(gè)和個(gè)經(jīng)典面試題前端開(kāi)發(fā)面試題如何面試前端工程師很重要個(gè)變態(tài)題解析如何通過(guò)餓了么面試輕 收集的一些前端面試題 從面試題發(fā)現(xiàn)不足,進(jìn)而查漏補(bǔ)缺,比通過(guò)面試更難得 1 BAT及各大互聯(lián)網(wǎng)公司2014前端筆試面試題--Html,Css篇 2 BAT...
閱讀 3477·2021-11-24 09:39
閱讀 1864·2021-11-17 09:33
閱讀 3821·2021-10-12 10:12
閱讀 5224·2021-09-22 15:51
閱讀 1166·2019-08-30 13:11
閱讀 3626·2019-08-30 10:59
閱讀 647·2019-08-30 10:48
閱讀 1375·2019-08-26 13:48