{"id":16751730,"url":"https://github.com/lq782655835/30-seconds-of-code","last_synced_at":"2025-04-10T15:52:14.800Z","repository":{"id":44023855,"uuid":"229185758","full_name":"lq782655835/30-seconds-of-code","owner":"lq782655835","description":"30-seconds-of-code for javascript utils","archived":false,"fork":false,"pushed_at":"2022-12-10T12:41:27.000Z","size":744,"stargazers_count":5,"open_issues_count":12,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-24T13:37:31.664Z","etag":null,"topics":["utils-lib"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lq782655835.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-12-20T03:50:34.000Z","updated_at":"2023-11-27T07:15:57.000Z","dependencies_parsed_at":"2023-01-26T02:01:48.942Z","dependency_job_id":null,"html_url":"https://github.com/lq782655835/30-seconds-of-code","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lq782655835%2F30-seconds-of-code","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lq782655835%2F30-seconds-of-code/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lq782655835%2F30-seconds-of-code/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lq782655835%2F30-seconds-of-code/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lq782655835","download_url":"https://codeload.github.com/lq782655835/30-seconds-of-code/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248245328,"owners_count":21071460,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["utils-lib"],"created_at":"2024-10-13T02:44:45.026Z","updated_at":"2025-04-10T15:52:14.766Z","avatar_url":"https://github.com/lq782655835.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 30-seconds-of-code ![](https://img.shields.io/badge/license-MIT-F44336.svg)\n\n## Install\n\n``` bash\nyarn add @springleo/30-seconds-of-code\n```\n\n## Usage\n\n``` js\nimport { copyToClipboard } from '@springleo/30-seconds-of-code'\ncopyToClipboard('hello world')\n```\n\n\n# API\n\nextend from https://github.com/ConardLi/30-seconds-of-code-Zh-CN\n\n## 目录\n\n### 🔌 Adapter\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`ary`](#ary)\n* [`call`](#call)\n* [`collectInto`](#collectinto)\n* [`flip`](#flip)\n* [`over`](#over)\n* [`overArgs`](#overargs)\n* [`pipeAsyncFunctions`](#pipeasyncfunctions)\n* [`pipeFunctions`](#pipefunctions)\n* [`promisify`](#promisify)\n* [`rearg`](#rearg)\n* [`spreadOver`](#spreadover)\n* [`unary`](#unary)\n\n\u003c/details\u003e\n\n### 📚 Array\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`all`](#all)\n* [`allEqual`](#allequal)\n* [`any`](#any)\n* [`arrayToCSV`](#arraytocsv)\n* [`bifurcate`](#bifurcate)\n* [`bifurcateBy`](#bifurcateby)\n* [`chunk`](#chunk)\n* [`compact`](#compact)\n* [`countBy`](#countby)\n* [`countOccurrences`](#countoccurrences)\n* [`deepFlatten`](#deepflatten)\n* [`difference`](#difference)\n* [`differenceBy`](#differenceby)\n* [`differenceWith`](#differencewith)\n* [`drop`](#drop)\n* [`dropRight`](#dropright)\n* [`dropRightWhile`](#droprightwhile)\n* [`dropWhile`](#dropwhile)\n* [`everyNth`](#everynth)\n* [`filterFalsy`](#filterfalsy)\n* [`filterNonUnique`](#filternonunique)\n* [`filterNonUniqueBy`](#filternonuniqueby)\n* [`findLast`](#findlast)\n* [`findLastIndex`](#findlastindex)\n* [`flatten`](#flatten)\n* [`forEachRight`](#foreachright)\n* [`groupBy`](#groupby)\n* [`head`](#head)\n* [`indexOfAll`](#indexofall)\n* [`initial`](#initial)\n* [`initialize2DArray`](#initialize2darray)\n* [`initializeArrayWithRange`](#initializearraywithrange)\n* [`initializeArrayWithRangeRight`](#initializearraywithrangeright)\n* [`initializeArrayWithValues`](#initializearraywithvalues)\n* [`initializeNDArray`](#initializendarray)\n* [`intersection`](#intersection)\n* [`intersectionBy`](#intersectionby)\n* [`intersectionWith`](#intersectionwith)\n* [`isSorted`](#issorted)\n* [`join`](#join)\n* [`JSONtoCSV`](#jsontocsv-)\n* [`last`](#last)\n* [`longestItem`](#longestitem)\n* [`mapObject`](#mapobject-)\n* [`maxN`](#maxn)\n* [`minN`](#minn)\n* [`none`](#none)\n* [`nthElement`](#nthelement)\n* [`offset`](#offset)\n* [`partition`](#partition)\n* [`permutations`](#permutations-)\n* [`pull`](#pull)\n* [`pullAtIndex`](#pullatindex-)\n* [`pullAtValue`](#pullatvalue-)\n* [`pullBy`](#pullby-)\n* [`reducedFilter`](#reducedfilter)\n* [`reduceSuccessive`](#reducesuccessive)\n* [`reduceWhich`](#reducewhich)\n* [`reject`](#reject)\n* [`remove`](#remove)\n* [`sample`](#sample)\n* [`sampleSize`](#samplesize)\n* [`shank`](#shank)\n* [`shuffle`](#shuffle)\n* [`similarity`](#similarity)\n* [`sortedIndex`](#sortedindex)\n* [`sortedIndexBy`](#sortedindexby)\n* [`sortedLastIndex`](#sortedlastindex)\n* [`sortedLastIndexBy`](#sortedlastindexby)\n* [`stableSort`](#stablesort-)\n* [`symmetricDifference`](#symmetricdifference)\n* [`symmetricDifferenceBy`](#symmetricdifferenceby)\n* [`symmetricDifferenceWith`](#symmetricdifferencewith)\n* [`tail`](#tail)\n* [`take`](#take)\n* [`takeRight`](#takeright)\n* [`takeRightWhile`](#takerightwhile)\n* [`takeWhile`](#takewhile)\n* [`toHash`](#tohash)\n* [`union`](#union)\n* [`unionBy`](#unionby)\n* [`unionWith`](#unionwith)\n* [`uniqueElements`](#uniqueelements)\n* [`uniqueElementsBy`](#uniqueelementsby)\n* [`uniqueElementsByRight`](#uniqueelementsbyright)\n* [`uniqueSymmetricDifference`](#uniquesymmetricdifference)\n* [`unzip`](#unzip)\n* [`unzipWith`](#unzipwith-)\n* [`without`](#without)\n* [`xProd`](#xprod)\n* [`zip`](#zip)\n* [`zipObject`](#zipobject)\n* [`zipWith`](#zipwith-)\n\n\u003c/details\u003e\n\n### 🌐 Browser\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`arrayToHtmlList`](#arraytohtmllist)\n* [`bottomVisible`](#bottomvisible)\n* [`copyToClipboard`](#copytoclipboard-)\n* [`counter`](#counter-)\n* [`createElement`](#createelement)\n* [`createEventHub`](#createeventhub-)\n* [`currentURL`](#currenturl)\n* [`detectDeviceType`](#detectdevicetype)\n* [`elementContains`](#elementcontains)\n* [`elementIsVisibleInViewport`](#elementisvisibleinviewport-)\n* [`getImages`](#getimages)\n* [`getScrollPosition`](#getscrollposition)\n* [`getStyle`](#getstyle)\n* [`hasClass`](#hasclass)\n* [`hashBrowser`](#hashbrowser-)\n* [`hide`](#hide)\n* [`httpsRedirect`](#httpsredirect)\n* [`insertAfter`](#insertafter)\n* [`insertBefore`](#insertbefore)\n* [`isBrowserTabFocused`](#isbrowsertabfocused)\n* [`nodeListToArray`](#nodelisttoarray)\n* [`observeMutations`](#observemutations-)\n* [`off`](#off)\n* [`on`](#on)\n* [`onUserInputChange`](#onuserinputchange-)\n* [`prefix`](#prefix)\n* [`recordAnimationFrames`](#recordanimationframes)\n* [`redirect`](#redirect)\n* [`runAsync`](#runasync-)\n* [`scrollToTop`](#scrolltotop)\n* [`setStyle`](#setstyle)\n* [`show`](#show)\n* [`smoothScroll`](#smoothscroll)\n* [`toggleClass`](#toggleclass)\n* [`triggerEvent`](#triggerevent)\n* [`UUIDGeneratorBrowser`](#uuidgeneratorbrowser)\n\n\u003c/details\u003e\n\n### ⏱️ Date\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`dayOfYear`](#dayofyear)\n* [`formatDuration`](#formatduration)\n* [`getColonTimeFromDate`](#getcolontimefromdate)\n* [`getDaysDiffBetweenDates`](#getdaysdiffbetweendates)\n* [`getMeridiemSuffixOfInteger`](#getmeridiemsuffixofinteger)\n* [`isAfterDate`](#isafterdate)\n* [`isBeforeDate`](#isbeforedate)\n* [`isSameDate`](#issamedate)\n* [`maxDate`](#maxdate)\n* [`minDate`](#mindate)\n* [`tomorrow`](#tomorrow)\n\n\u003c/details\u003e\n\n### 🎛️ Function\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`attempt`](#attempt)\n* [`bind`](#bind)\n* [`bindKey`](#bindkey)\n* [`chainAsync`](#chainasync)\n* [`compose`](#compose)\n* [`composeRight`](#composeright)\n* [`converge`](#converge)\n* [`curry`](#curry)\n* [`debounce`](#debounce)\n* [`defer`](#defer)\n* [`delay`](#delay)\n* [`functionName`](#functionname)\n* [`hz`](#hz)\n* [`memoize`](#memoize-)\n* [`negate`](#negate)\n* [`once`](#once)\n* [`partial`](#partial)\n* [`partialRight`](#partialright)\n* [`runPromisesInSeries`](#runpromisesinseries)\n* [`sleep`](#sleep)\n* [`throttle`](#throttle-)\n* [`times`](#times)\n* [`uncurry`](#uncurry)\n* [`unfold`](#unfold)\n* [`when`](#when)\n\n\u003c/details\u003e\n\n### ➗ Math\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`approximatelyEqual`](#approximatelyequal)\n* [`average`](#average)\n* [`averageBy`](#averageby)\n* [`binomialCoefficient`](#binomialcoefficient)\n* [`clampNumber`](#clampnumber)\n* [`degreesToRads`](#degreestorads)\n* [`digitize`](#digitize)\n* [`distance`](#distance)\n* [`elo`](#elo-)\n* [`factorial`](#factorial)\n* [`fibonacci`](#fibonacci)\n* [`gcd`](#gcd)\n* [`geometricProgression`](#geometricprogression)\n* [`hammingDistance`](#hammingdistance)\n* [`inRange`](#inrange)\n* [`isDivisible`](#isdivisible)\n* [`isEven`](#iseven)\n* [`isNegativeZero`](#isnegativezero)\n* [`isPrime`](#isprime)\n* [`lcm`](#lcm)\n* [`luhnCheck`](#luhncheck-)\n* [`maxBy`](#maxby)\n* [`median`](#median)\n* [`midpoint`](#midpoint)\n* [`minBy`](#minby)\n* [`percentile`](#percentile)\n* [`powerset`](#powerset)\n* [`primes`](#primes)\n* [`radsToDegrees`](#radstodegrees)\n* [`randomIntArrayInRange`](#randomintarrayinrange)\n* [`randomIntegerInRange`](#randomintegerinrange)\n* [`randomNumberInRange`](#randomnumberinrange)\n* [`round`](#round)\n* [`sdbm`](#sdbm)\n* [`standardDeviation`](#standarddeviation)\n* [`sum`](#sum)\n* [`sumBy`](#sumby)\n* [`sumPower`](#sumpower)\n* [`toSafeInteger`](#tosafeinteger)\n\n\u003c/details\u003e\n\n### 📦 Node\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`atob`](#atob)\n* [`btoa`](#btoa)\n* [`colorize`](#colorize)\n* [`createDirIfNotExists`](#createdirifnotexists)\n* [`hasFlags`](#hasflags)\n* [`hashNode`](#hashnode)\n* [`isDuplexStream`](#isduplexstream)\n* [`isReadableStream`](#isreadablestream)\n* [`isStream`](#isstream)\n* [`isTravisCI`](#istravisci)\n* [`isWritableStream`](#iswritablestream)\n* [`JSONToFile`](#jsontofile)\n* [`readFileLines`](#readfilelines)\n* [`untildify`](#untildify)\n* [`UUIDGeneratorNode`](#uuidgeneratornode)\n\n\u003c/details\u003e\n\n### 🗃️ Object\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`bindAll`](#bindall)\n* [`deepClone`](#deepclone)\n* [`deepFreeze`](#deepfreeze)\n* [`deepMapKeys`](#deepmapkeys-)\n* [`defaults`](#defaults)\n* [`dig`](#dig)\n* [`equals`](#equals-)\n* [`findKey`](#findkey)\n* [`findLastKey`](#findlastkey)\n* [`flattenObject`](#flattenobject)\n* [`forOwn`](#forown)\n* [`forOwnRight`](#forownright)\n* [`functions`](#functions)\n* [`get`](#get)\n* [`invertKeyValues`](#invertkeyvalues)\n* [`lowercaseKeys`](#lowercasekeys)\n* [`mapKeys`](#mapkeys)\n* [`mapValues`](#mapvalues)\n* [`matches`](#matches)\n* [`matchesWith`](#matcheswith)\n* [`merge`](#merge)\n* [`nest`](#nest)\n* [`objectFromPairs`](#objectfrompairs)\n* [`objectToPairs`](#objecttopairs)\n* [`omit`](#omit)\n* [`omitBy`](#omitby)\n* [`orderBy`](#orderby)\n* [`pick`](#pick)\n* [`pickBy`](#pickby)\n* [`renameKeys`](#renamekeys)\n* [`shallowClone`](#shallowclone)\n* [`size`](#size)\n* [`transform`](#transform)\n* [`truthCheckCollection`](#truthcheckcollection)\n* [`unflattenObject`](#unflattenobject-)\n\n\u003c/details\u003e\n\n### 📜 String\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`byteSize`](#bytesize)\n* [`capitalize`](#capitalize)\n* [`capitalizeEveryWord`](#capitalizeeveryword)\n* [`compactWhitespace`](#compactwhitespace)\n* [`CSVToArray`](#csvtoarray)\n* [`CSVToJSON`](#csvtojson-)\n* [`decapitalize`](#decapitalize)\n* [`escapeHTML`](#escapehtml)\n* [`escapeRegExp`](#escaperegexp)\n* [`fromCamelCase`](#fromcamelcase)\n* [`indentString`](#indentstring)\n* [`isAbsoluteURL`](#isabsoluteurl)\n* [`isAnagram`](#isanagram)\n* [`isLowerCase`](#islowercase)\n* [`isUpperCase`](#isuppercase)\n* [`mapString`](#mapstring)\n* [`mask`](#mask)\n* [`pad`](#pad)\n* [`palindrome`](#palindrome)\n* [`pluralize`](#pluralize)\n* [`removeNonASCII`](#removenonascii)\n* [`reverseString`](#reversestring)\n* [`sortCharactersInString`](#sortcharactersinstring)\n* [`splitLines`](#splitlines)\n* [`stringPermutations`](#stringpermutations-)\n* [`stripHTMLTags`](#striphtmltags)\n* [`toCamelCase`](#tocamelcase)\n* [`toKebabCase`](#tokebabcase)\n* [`toSnakeCase`](#tosnakecase)\n* [`toTitleCase`](#totitlecase)\n* [`truncateString`](#truncatestring)\n* [`unescapeHTML`](#unescapehtml)\n* [`URLJoin`](#urljoin-)\n* [`words`](#words)\n\n\u003c/details\u003e\n\n### 📃 Type\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`getType`](#gettype)\n* [`is`](#is)\n* [`isArrayLike`](#isarraylike)\n* [`isBoolean`](#isboolean)\n* [`isEmpty`](#isempty)\n* [`isFunction`](#isfunction)\n* [`isNil`](#isnil)\n* [`isNull`](#isnull)\n* [`isNumber`](#isnumber)\n* [`isObject`](#isobject)\n* [`isObjectLike`](#isobjectlike)\n* [`isPlainObject`](#isplainobject)\n* [`isPrimitive`](#isprimitive)\n* [`isPromiseLike`](#ispromiselike)\n* [`isString`](#isstring)\n* [`isSymbol`](#issymbol)\n* [`isUndefined`](#isundefined)\n* [`isValidJSON`](#isvalidjson)\n\n\u003c/details\u003e\n\n### 🔧 Utility\n\n\u003cdetails\u003e\n\u003csummary\u003e查看目录\u003c/summary\u003e\n\n* [`castArray`](#castarray)\n* [`cloneRegExp`](#cloneregexp)\n* [`coalesce`](#coalesce)\n* [`coalesceFactory`](#coalescefactory)\n* [`extendHex`](#extendhex)\n* [`getURLParameters`](#geturlparameters)\n* [`hexToRGB`](#hextorgb-)\n* [`httpGet`](#httpget)\n* [`httpPost`](#httppost)\n* [`isBrowser`](#isbrowser)\n* [`mostPerformant`](#mostperformant)\n* [`nthArg`](#ntharg)\n* [`parseCookie`](#parsecookie)\n* [`prettyBytes`](#prettybytes-)\n* [`randomHexColorCode`](#randomhexcolorcode)\n* [`RGBToHex`](#rgbtohex)\n* [`serializeCookie`](#serializecookie)\n* [`timeTaken`](#timetaken)\n* [`toCurrency`](#tocurrency)\n* [`toDecimalMark`](#todecimalmark)\n* [`toOrdinalSuffix`](#toordinalsuffix)\n* [`validateNumber`](#validatenumber)\n* [`yesNo`](#yesno)\n\n\u003c/details\u003e\n\n\n---\n\n## 🔌 Adapter\n\n### ary\n\n创建一个可以接收n个参数的函数, 忽略其他额外的参数。\n\n调用提供的函数`fn`,参数最多为n个, 使用 `Array.prototype.slice(0,n)` 和展开操作符 (`...`)。\n\n```js\nconst ary = (fn, n) =\u003e (...args) =\u003e fn(...args.slice(0, n));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst firstTwoMax = ary(Math.max, 2);\n[[2, 6, 'a'], [8, 4, 6], [10]].map(x =\u003e firstTwoMax(...x)); // [6, 8, 10]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### call\n\n给定一个key和一组参数，给定一个上下文时调用它们。主要用于合并。\n\n使用闭包调用上下文中key对应的值，\b即带有存储参数的函数。\n\n```js\nconst call = (key, ...args) =\u003e context =\u003e context[key](...args);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nPromise.resolve([1, 2, 3])\n  .then(call('map', x =\u003e 2 * x))\n  .then(console.log); // [ 2, 4, 6 ]\nconst map = call.bind(null, 'map');\nPromise.resolve([1, 2, 3])\n  .then(map(x =\u003e 2 * x))\n  .then(console.log); // [ 2, 4, 6 ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### collectInto\n\n将一个接收数组参数的函数改变为可变参数的函数。\n\n给定一个函数，返回一个闭包，该闭包将所有输入收集到一个数组接受函数中。\n\n```js\nconst collectInto = fn =\u003e (...args) =\u003e fn(args);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst Pall = collectInto(Promise.all.bind(Promise));\nlet p1 = Promise.resolve(1);\nlet p2 = Promise.resolve(2);\nlet p3 = new Promise(resolve =\u003e setTimeout(resolve, 2000, 3));\nPall(p1, p2, p3).then(console.log); // [1, 2, 3] (after about 2 seconds)\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### flip\n\n\bFlip以一个函数作为参数，然后把第一个参数作为最后一个参数。\n\n返回一个可变参数的闭包，在应用其他参数前，先把第一个以外的其他参数作为第一个参数。\n\n\n```js\nconst flip = fn =\u003e (first, ...rest) =\u003e fn(...rest, first);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlet a = { name: 'John Smith' };\nlet b = {};\nconst mergeFrom = flip(Object.assign);\nlet mergePerson = mergeFrom.bind(null, a);\nmergePerson(b); // == b\nb = {};\nObject.assign(b, a); // == b\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### over\n\n创建一个函数，这个函数可以调用每一个被传入的并且才有参数的函数，然后返回结果。\n\n使用 `Array.prototype.map()` 和 `Function.prototype.apply()`将每个函数应用给定的参数。\n\n```js\nconst over = (...fns) =\u003e (...args) =\u003e fns.map(fn =\u003e fn.apply(null, args));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst minMax = over(Math.min, Math.max);\nminMax(1, 2, 3, 4, 5); // [1,5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### overArgs\n\n创建一个函数，它可以调用提供的被转换参数的函数。\n\n使用`Array.prototype.map()`将`transforms`应用于`args`，并结合扩展运算符(`…`)将转换后的参数传递给`fn`。\n\n\n```js\nconst overArgs = (fn, transforms) =\u003e (...args) =\u003e fn(...args.map((val, i) =\u003e transforms[i](val)));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst square = n =\u003e n * n;\nconst double = n =\u003e n * 2;\nconst fn = overArgs((x, y) =\u003e [x, y], [square, double]);\nfn(9, 3); // [81, 6]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### pipeAsyncFunctions\n\n为异步函数执行从左到右的函数组合。\n\n在扩展操作符(`…`)中使用`Array.prototype.reduce() `来使用`Promise.then()`执行从左到右的函数组合。\n这些函数可以返回简单值、`Promise`的组合，也可以定义为通过`await`返回的`async`值。\n所有函数必须是一元的。\n\n```js\nconst pipeAsyncFunctions = (...fns) =\u003e arg =\u003e fns.reduce((p, f) =\u003e p.then(f), Promise.resolve(arg));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\n\nconst sum = pipeAsyncFunctions(\n  x =\u003e x + 1,\n  x =\u003e new Promise(resolve =\u003e setTimeout(() =\u003e resolve(x + 2), 1000)),\n  x =\u003e x + 3,\n  async x =\u003e (await x) + 4\n);\n(async() =\u003e {\n  console.log(await sum(5)); // 15 (after one second)\n})();\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### pipeFunctions\n\n执行从左到右的函数组合。\n\n在展开操作符(`…`)中使用`Array.prototype.reduce()`来执行从左到右的函数组合。\n第一个(最左边的)函数可以接受一个或多个参数; 其余的函数必须是一元的。\n\n```js\nconst pipeFunctions = (...fns) =\u003e fns.reduce((f, g) =\u003e (...args) =\u003e g(f(...args)));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst add5 = x =\u003e x + 5;\nconst multiply = (x, y) =\u003e x * y;\nconst multiplyAndAdd5 = pipeFunctions(multiply, add5);\nmultiplyAndAdd5(5, 2); // 15\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### promisify\n\n把一个异步函数转换成返回promise的。\n\n使用局部套用返回一个函数，该函数返回一个调用原始函数的`Promise`。\n使用的`...`操作符来传入所有参数。\n\n```js\nconst promisify = func =\u003e (...args) =\u003e\n  new Promise((resolve, reject) =\u003e\n    func(...args, (err, result) =\u003e (err ? reject(err) : resolve(result)))\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst delay = promisify((d, cb) =\u003e setTimeout(cb, d));\ndelay(2000).then(() =\u003e console.log('Hi!')); // // Promise resolves after 2s\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### rearg\n\n创建一个调用提供的函数的函数，该函数的参数按照指定的索引排列。\n\n利用 `Array.prototype.map()` 根据 `indexes` 和展开操作符 (`...`) 对参数进行重新排序，将转换后的参数传递给 `fn`。\n\n```js\nconst rearg = (fn, indexes) =\u003e (...args) =\u003e fn(...indexes.map(i =\u003e args[i]));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nvar rearged = rearg(\n  function(a, b, c) {\n    return [a, b, c];\n  },\n  [2, 0, 1]\n);\nrearged('b', 'c', 'a'); // ['a', 'b', 'c']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### spreadOver\n\n接受一个可变参数函数并返回一个闭包，该闭包接受一个参数数组以映射到函数的输入。\n\n使用闭包和扩展操作符(`…`)将参数数组映射到函数的输入。\n\n```js\nconst spreadOver = fn =\u003e argsArr =\u003e fn(...argsArr);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst arrayMax = spreadOver(Math.max);\narrayMax([1, 2, 3]); // 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### unary\n\n创建一个最多接受一个参数的函数，忽略任何其他参数。\n\n只把第一个参数传递给要调用的函数`fn`。\n\n```js\nconst unary = fn =\u003e val =\u003e fn(val);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\n['6', '8', '10'].map(unary(parseInt)); // [6, 8, 10]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n\n---\n\n## 📚 Array\n\n### all\n\n如果被提供的断言函数接收数组中每个元素作为参数都返回`true`，则返回`true`，否则返回`false`。\n\n\n使用 `Array.prototype.every()`来测试是否第二个参数`fn`以集合中每个元素作为参数都返回`true`，使用`Boolean`作为默认值。\n\n```js\nconst all = (arr, fn = Boolean) =\u003e arr.every(fn);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nall([4, 2, 3], x =\u003e x \u003e 1); // true\nall([1, 2, 3]); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### allEqual\n\n检查是否数组中所有的元素都是相等的。\n\n使用 `Array.prototype.every()` 来检测是否数组中的所有元素都和第一个元素相等。\n\n```js\nconst allEqual = arr =\u003e arr.every(val =\u003e val === arr[0]);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nallEqual([1, 2, 3, 4, 5, 6]); // false\nallEqual([1, 1, 1, 1]); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### any\n\n如果被提供的断言函数接收数组中任意一个元素作为参数都返回`true`，则返回`true`，否则返回`false`。\n\n使用 `Array.prototype.every()`来测试是否第二个参数`fn`以集合中任意一个元素作为参数都返回`true`，使用`Boolean`作为默认值。\n\n```js\nconst any = (arr, fn = Boolean) =\u003e arr.some(fn);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nany([0, 1, 2, 0], x =\u003e x \u003e= 2); // true\nany([0, 0, 1, 0]); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### arrayToCSV\n\n将2D数组转换为逗号分隔值(CSV)字符串。\n\n使用 `Array.prototype.map()` 和 `Array.prototype.join(delimiter)` 将一个一维数组转换为字符串。\n\n使用 `Array.prototype.join('\\n')` 将所有行合并成CSV字符串, 用换行符分割每一行。\n\n如果没有第二哥参数, `delimiter`会使用一个默认分隔符 `,`.\n\n```js\nconst arrayToCSV = (arr, delimiter = ',') =\u003e\n  arr.map(v =\u003e v.map(x =\u003e `\"${x}\"`).join(delimiter)).join('\\n');\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\narrayToCSV([['a', 'b'], ['c', 'd']]); // '\"a\",\"b\"\\n\"c\",\"d\"'\narrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '\"a\";\"b\"\\n\"c\";\"d\"'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### bifurcate\n\n将数据分为两组，如果元素在 `filter`数组中对应的是`true`，集合中相应的元素应加入第一个数组，否则加入第二个数组。\n\n基于`filter`使用`Array.prototype.reduce()` 和 `Array.prototype.push()`将元素分组。\n\n```js\nconst bifurcate = (arr, filter) =\u003e\n  arr.reduce((acc, val, i) =\u003e (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nbifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); // [ ['beep', 'boop', 'bar'], ['foo'] ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### bifurcateBy\n\n根据断言函数将数据分成两组，断言函数将指定集合中的元素属于哪个组。如果断言函数返回`true`，元素加入第一个数组，否则加入第二个数组。\n\n给予`fn`接收元素的返回值，使用`Array.prototype.reduce()` 和 `Array.prototype.push()`将元素分组。\n\n```js\nconst bifurcateBy = (arr, fn) =\u003e\n  arr.reduce((acc, val, i) =\u003e (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nbifurcateBy(['beep', 'boop', 'foo', 'bar'], x =\u003e x[0] === 'b'); // [ ['beep', 'boop', 'bar'], ['foo'] ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### chunk\n\n将数组分成指定大小的较小数组。\n\n使用 `Array.from()`创建一个新的数组，该数组与将要生成的块的数量相匹配。\n使用 `Array.prototype.slice()` 将新数组的每个元素映射到长度为`size`的块。\n如果原始的数组不能被均匀的分割，最后的一块将包含剩余的元素。\n\n\n```js\nconst chunk = (arr, size) =\u003e\n  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =\u003e\n    arr.slice(i * size, i * size + size)\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nchunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### compact\n\n删除数组中错误的元素\n\n使用 `Array.prototype.filter()` 过滤掉错误的元素 (`false`, `null`, `0`, `\"\"`, `undefined`,  `NaN`).\n\n```js\nconst compact = arr =\u003e arr.filter(Boolean);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncompact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### countBy\n\n基于给定的函数将数组中的元素进行分组，并返回每个组中的元素数。\n\n使用`Array.prototype.map()`来将数组中的每个元素映射到函数或属性名。\n使用 `Array.prototype.reduce()` 创建一个对象，其中的键是从映射结果生成的。\n\n\n```js\nconst countBy = (arr, fn) =\u003e\n  arr.map(typeof fn === 'function' ? fn : val =\u003e val[fn]).reduce((acc, val) =\u003e {\n    acc[val] = (acc[val] || 0) + 1;\n    return acc;\n  }, {});\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncountBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}\ncountBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### countOccurrences\n\n计算数组中某个元素出现的次数。\n\nUse `Array.prototype.reduce()`在每次遇到数组中的特定值时递增计数器。\n```js\nconst countOccurrences = (arr, val) =\u003e arr.reduce((a, v) =\u003e (v === val ? a + 1 : a), 0);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncountOccurrences([1, 1, 2, 1, 2, 3], 1); // 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### deepFlatten\n\n将一个多层嵌套的数组转转换成一个一元数组。\n\n使用递归.\nUse `Array.prototype.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array.\n使用 `Array.prototype.concat()` 和一个空数组(`[]`)以及展开运算符(`...`)来平铺一个数组。\n当每个元素还是一个数字时，递归铺平他。\n\n```js\nconst deepFlatten = arr =\u003e [].concat(...arr.map(v =\u003e (Array.isArray(v) ? deepFlatten(v) : v)));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndeepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### difference\n\n返回两个数组间的差异值。\n\n从数组`b`中创建一个 `Set` ，然后用使用另一个数组`a`的`Array.prototype.filter()` 方法过滤掉`b`中的元素。\n\n```js\nconst difference = (a, b) =\u003e {\n  const s = new Set(b);\n  return a.filter(x =\u003e !s.has(x));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndifference([1, 2, 3], [1, 2, 4]); // [3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### differenceBy\n\n将提供的函数应用于两个数组的每个数组元素后，返回两个数组中不同的元素。\n\n通过`b`中的每个元素调用 `fn`后创建一个 `Set` ，然后将`Array.prototype.filter()` 与`fn`调用后的`a`结合使用，只保留先前创建的集合中不包含的值。\n\n\n```js\nconst differenceBy = (a, b, fn) =\u003e {\n  const s = new Set(b.map(fn));\n  return a.filter(x =\u003e !s.has(fn(x)));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]\ndifferenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v =\u003e v.x); // [ { x: 2 } ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### differenceWith\n\n筛选出比较器函数不返回`true`的数组中的所有值。\n\n使用 `Array.prototype.filter()` 和 `Array.prototype.findIndex()` 查找合适的值。\n\n```js\nconst differenceWith = (arr, val, comp) =\u003e arr.filter(a =\u003e val.findIndex(b =\u003e comp(a, b)) === -1);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndifferenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) =\u003e Math.round(a) === Math.round(b)); // [1, 1.2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### drop\n\n返回一个新数组，从原数组左边删除`n`个元素。\n\n使用 `Array.prototype.slice()` 从左侧删除指定数量的元素。\n\n```js\nconst drop = (arr, n = 1) =\u003e arr.slice(n);\n```\n\n\u003e slice(n) 表示取数组下标n以后的元素（含n）\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndrop([1, 2, 3]); // [2,3]\ndrop([1, 2, 3], 2); // [3]\ndrop([1, 2, 3], 42); // []\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### dropRight\n\n返回一个新数组，从原数组右边删除`n`个元素。\n\n使用 `Array.prototype.slice()`从右边删除指定数目的元素。\n\n```js\nconst dropRight = (arr, n = 1) =\u003e arr.slice(0, -n);\n```\n\n\u003e slice(0, -n) 表示取数组第一个到倒数第n个元素（不含-n）\n\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndropRight([1, 2, 3]); // [1,2]\ndropRight([1, 2, 3], 2); // [1]\ndropRight([1, 2, 3], 42); // []\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### dropRightWhile\n\n从数组尾部移除数组中的元素，直到传递的函数返回`true`。返回数组中剩余的元素。\n\n遍历数组，使用`Array.prototype.slice()`删除数组的最后一个元素，直到函数的返回值为`true`。返回剩余的元素。\n\n\n```js\nconst dropRightWhile = (arr, func) =\u003e {\n  while (arr.length \u003e 0 \u0026\u0026 !func(arr[arr.length - 1])) arr = arr.slice(0, -1);\n  return arr;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndropRightWhile([1, 2, 3, 4], n =\u003e n \u003c 3); // [1, 2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### dropWhile\n\n移除数组中的元素，直到传递的函数返回`true`。返回数组中剩余的元素。\n\n遍历数组，使用`Array.prototype.slice()`删除数组的第一个元素，直到函数的返回值为`true`。返回剩余的元素。\n\n```js\nconst dropWhile = (arr, func) =\u003e {\n  while (arr.length \u003e 0 \u0026\u0026 !func(arr[0])) arr = arr.slice(1);\n  return arr;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndropWhile([1, 2, 3, 4], n =\u003e n \u003e= 3); // [3,4]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### everyNth\n\n返回数组中所有下标是n的倍数的元素。\n\n使用 `Array.prototype.filter()` 创建包含给定数组中所有下标是n的倍数的元素的新数组。\n\n```js\nconst everyNth = (arr, nth) =\u003e arr.filter((e, i) =\u003e i % nth === nth - 1);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\neveryNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### filterFalsy\n\n把数组中的`虚值`过滤掉。\n\n使用 `Array.prototype.filter()`创建一个只包含`真值`的新数组。 \n\n\n```js\nconst filterFalsy = arr =\u003e arr.filter(Boolean);\n```\n\n\u003e `falsy`(虚值)是在` Boolean `上下文中已认定可转换为‘假‘的值。例如：false，0，\"\"，null，undefined 和 NaN 。\n\n\u003e `Truthy` (真值)指的是在 布尔值 上下文中转换后的值为真的值。所有值都是真值，除非它们被定义为 `falsy`。\n\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nfilterFalsy(['', true, {}, false, 'sample', 1, 0]); // [true, {}, 'sample', 1]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### filterNonUnique\n\n过滤掉数组中重复的值。\n\n使用 `Array.prototype.filter()`创建一个只包含谓唯一值的数组。\n\n\n```js\nconst filterNonUnique = arr =\u003e arr.filter(i =\u003e arr.indexOf(i) === arr.lastIndexOf(i));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nfilterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### filterNonUniqueBy\n\n基于给定的比较器函数，过滤掉数组中重复的元素。\n\n使用`Array.prototype.filter()` 和 `Array.prototype.every()` 创建一个新数组，该数组只包含唯一值，基于给定的比较器函数 `fn`。\n\n比较器函数接收四个参数：正在被比较的两个元素和他们的索引。\n\n\n```js\nconst filterNonUniqueBy = (arr, fn) =\u003e\n  arr.filter((v, i) =\u003e arr.every((x, j) =\u003e (i === j) === fn(v, x, i, j)));\n```\n\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nfilterNonUniqueBy(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) =\u003e a.id == b.id\n); // [ { id: 2, value: 'c' } ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### findLast\n\n返回所提供函数返回`真值`的最后一个元素。\n\n使用 `Array.prototype.filter()` 将调用`fn`后返回`虚值`的元素过滤掉, 然后调用`Array.prototype.pop()` 来获取最后一个元素。\n\n```js\nconst findLast = (arr, fn) =\u003e arr.filter(fn).pop();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nfindLast([1, 2, 3, 4], n =\u003e n % 2 === 1); // 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### findLastIndex\n\n返回所提供函数返回`真值`的最后一个元素的索引。\n\n使用 `Array.prototype.map()` 将每个元素映射到具有其索引和值的数组。\n使用 `Array.prototype.filter()` 将调用`fn`后返回`虚值`的元素过滤掉, 然后调用`Array.prototype.pop()` 来获取最后一个元素的索引。\n\n```js\nconst findLastIndex = (arr, fn) =\u003e\n  arr\n    .map((val, i) =\u003e [i, val])\n    .filter(([i, val]) =\u003e fn(val, i, arr))\n    .pop()[0];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nfindLastIndex([1, 2, 3, 4], n =\u003e n % 2 === 1); // 2 (index of the value 3)\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### flatten\n\n根据指定的深度展平一个数组。\n\n使用递归，每层递归 `depth` 递减1。\n使用 `Array.prototype.reduce()` 和 `Array.prototype.concat()` 来合并数组或者元素。\n基本情况下，当`depth` 等于1时停止递归。\n忽略第二个参数的情况下， `depth` 默认为1（单层展开）。\n\n```js\nconst flatten = (arr, depth = 1) =\u003e\n  arr.reduce((a, v) =\u003e a.concat(depth \u003e 1 \u0026\u0026 Array.isArray(v) ? flatten(v, depth - 1) : v), []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nflatten([1, [2], 3, 4]); // [1, 2, 3, 4]\nflatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### forEachRight\n\n对数组中的每个元素执行一次所提供的函数，从数组的最后一个元素开始。\n\n\n使用 `Array.prototype.slice(0)` 克隆给定的数组，并使用`Array.prototype.reverse()` 将它反转，然后使用`Array.prototype.forEach()`遍历反转后的数组。\n\n\n```js\nconst forEachRight = (arr, callback) =\u003e\n  arr\n    .slice(0)\n    .reverse()\n    .forEach(callback);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nforEachRight([1, 2, 3, 4], val =\u003e console.log(val)); // '4', '3', '2', '1'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### groupBy\n\n基于给定的函数将数组分组。\n\n使用 `Array.prototype.map()` 将组数中的值映射到一个函数或者属性名。\n\n使用 `Array.prototype.reduce()` 创建一个对象，其中的键由映射的结果生成。\n\n```js\nconst groupBy = (arr, fn) =\u003e\n  arr.map(typeof fn === 'function' ? fn : val =\u003e val[fn]).reduce((acc, val, i) =\u003e {\n    acc[val] = (acc[val] || []).concat(arr[i]);\n    return acc;\n  }, {});\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ngroupBy([6.1, 4.2, 6.3], Math.floor); // {4: [4.2], 6: [6.1, 6.3]}\ngroupBy(['one', 'two', 'three'], 'length'); // {3: ['one', 'two'], 5: ['three']}\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### head\n\n返回列表的头部\n\n使用 `arr[0]` 返回传递数组的第一个元素。\n\n```js\nconst head = arr =\u003e arr[0];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nhead([1, 2, 3]); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### indexOfAll\n\n返回一个数组中所有 `val` 的索引。\n如果 `val` 不存在，返回 `[]` 。\n\n使用 `Array.prototype.reduce()` 遍历元素，将匹配的元素索引存储下来，返回索引数组。\n\n```js\nconst indexOfAll = (arr, val) =\u003e arr.reduce((acc, el, i) =\u003e (el === val ? [...acc, i] : acc), []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nindexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]\nindexOfAll([1, 2, 3], 4); // []\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initial\n\n返回数组中除最后一个元素外的所有元素。\n\n使用 `arr.slice(0,-1)` 返回数组中除最后一个元素外的所有元素。\n\n```js\nconst initial = arr =\u003e arr.slice(0, -1);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitial([1, 2, 3]); // [1,2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initialize2DArray\n\n根据给定的宽、高和值初始化一个二维数组。\n\n使用 `Array.prototype.map()` 生成`h`行，其中每一行都是大小为`w`的新数组，并用值初始化。如果没有提供该值，则默认为`null`。\n\n```js\nconst initialize2DArray = (w, h, val = null) =\u003e\n  Array.from({ length: h }).map(() =\u003e Array.from({ length: w }).fill(val));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitialize2DArray(2, 2, 0); // [[0,0], [0,0]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initializeArrayWithRange\n\n初始化一个数组，该数组包括从 `start` 到 `end` 指定范围的数字，并且包括共同的公差 `step` 。\n\n使用 `Array.from()` 创建一个所需长度 `(end - start + 1)/step` 的数组，然后指定一个匹配函数将指定范围内的所需值填充到数组中。\n\n你可以省略 `start` 使用默认值`0`;\n你可以省略 `step` 使用默认值`1`;\n```js\nconst initializeArrayWithRange = (end, start = 0, step = 1) =\u003e\n  Array.from({ length: Math.ceil((end - start + 1) / step) }, (v, i) =\u003e i * step + start);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitializeArrayWithRange(5); // [0,1,2,3,4,5]\ninitializeArrayWithRange(7, 3); // [3,4,5,6,7]\ninitializeArrayWithRange(9, 0, 2); // [0,2,4,6,8]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initializeArrayWithRangeRight\n\n初始化一个数组，该数组包括从 `start` 到 `end` 指定范围的数字（反向的），并且包括共同的公差 `step` 。\n\n使用 `Array.from(Math.ceil((end+1-start)/step))` 创建一个期望长度的数组（为了兼容结束，元素的数量等同于`(end-start)/step` 或 `(end+1-start)/step`），使用`Array.prototype.map()`来填充期望范围内的值。\n\n你可以省略 `start` 使用默认值`0`。\n你可以省略 `step` 使用默认值`1`。\n```js\nconst initializeArrayWithRangeRight = (end, start = 0, step = 1) =\u003e\n  Array.from({ length: Math.ceil((end + 1 - start) / step) }).map(\n    (v, i, arr) =\u003e (arr.length - i - 1) * step + start\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitializeArrayWithRangeRight(5); // [5,4,3,2,1,0]\ninitializeArrayWithRangeRight(7, 3); // [7,6,5,4,3]\ninitializeArrayWithRangeRight(9, 0, 2); // [8,6,4,2,0]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initializeArrayWithValues\n\n初始化一个数组，并且使用指定的值填充它。\n\n使用 `Array(n)` 创建一个期望长度的数组，使用 `fill(v)` 用期望的值填充数组。\n\n你可以省略参数 `val` 使用默认值`0`。\n\n\n```js\nconst initializeArrayWithValues = (n, val = 0) =\u003e Array(n).fill(val);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### initializeNDArray\n\n使用给定的值创建一个n维数组。\n\n使用递归。使用 `Array.prototype.map()` 来生成行，这些行每一个都是使用`initializeNDArray`初始化的新数组。\n\n```js\nconst initializeNDArray = (val, ...args) =\u003e\n  args.length === 0\n    ? val\n    : Array.from({ length: args[0] }).map(() =\u003e initializeNDArray(val, ...args.slice(1)));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninitializeNDArray(1, 3); // [1,1,1]\ninitializeNDArray(5, 2, 2, 2); // [[[5,5],[5,5]],[[5,5],[5,5]]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### intersection\n\n返回两个数组中都存在的元素列表。\n\n从 `b`创建一个 `Set` ，然后在`a`上使用`Array.prototype.filter()`来只保留 `b`中包含的元素。\n\n```js\nconst intersection = (a, b) =\u003e {\n  const s = new Set(b);\n  return a.filter(x =\u003e s.has(x));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nintersection([1, 2, 3], [4, 3, 2]); // [2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### intersectionBy\n\n将提供的函数应应用到两个数组的每个元素上，然后返回两个数组中都存在的元素列表\n\n通过将 `fn` 应用到 `b`的所有元素来创建一个 `Set`，然后在 `a` 上调用 `Array.prototype.filter()` 来只保留调用 `fn` 后 `b` 中包含的元素。\n\n```js\nconst intersectionBy = (a, b, fn) =\u003e {\n  const s = new Set(b.map(fn));\n  return a.filter(x =\u003e s.has(fn(x)));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nintersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### intersectionWith\n\n返回两个数组中都存在的元素列表，使用给定的比较函数。\n\n结合使用`Array.prototype.filter()`和 `Array.prototype.findIndex()` 来确定交叉值。\n\n```js\nconst intersectionWith = (a, b, comp) =\u003e a.filter(x =\u003e b.findIndex(y =\u003e comp(x, y)) !== -1);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nintersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) =\u003e Math.round(a) === Math.round(b)); // [1.5, 3, 0]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### isSorted\n\n如果数组是升序排序的，返回 `1` ，如果数组是降序排序的返回 `-1`，如果数组没有排序返回`0` 。\n\n计算前两个元素的顺序 `direction`。使用 `Object.entries()` 来遍历数组，病成对比较。如果 `direction` 改变，返回 `0` ，如果到达最后一个元素，返回 `direction` 。\n\n```js\nconst isSorted = arr =\u003e {\n  let direction = -(arr[0] - arr[1]);\n  for (let [i, val] of arr.entries()) {\n    direction = !direction ? -(arr[i - 1] - arr[i]) : direction;\n    if (i === arr.length - 1) return !direction ? 0 : direction;\n    else if ((val - arr[i + 1]) * direction \u003e 0) return 0;\n  }\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nisSorted([0, 1, 2, 2]); // 1\nisSorted([4, 3, 2]); // -1\nisSorted([4, 3, 5]); // 0\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### join\n\n将数组中所有的元素连接成一个字符串，并返回这个字符串。使用一个分隔符和结束分隔符。\n\n使用 `Array.prototype.reduce()` 将元素合并成字符串。\n忽略第二个参数，`separator`，默认情况下使用一个默认分隔符`','`。\n忽略第三个参数， `end`，使用和`separator`相同的值作为默认值。\n\n```js\nconst join = (arr, separator = ',', end = separator) =\u003e\n  arr.reduce(\n    (acc, val, i) =\u003e\n      i === arr.length - 2\n        ? acc + val + end\n        : i === arr.length - 1\n          ? acc + val\n          : acc + val + separator,\n    ''\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\njoin(['pen', 'pineapple', 'apple', 'pen'], ',', '\u0026'); // \"pen,pineapple,apple\u0026pen\"\njoin(['pen', 'pineapple', 'apple', 'pen'], ','); // \"pen,pineapple,apple,pen\"\njoin(['pen', 'pineapple', 'apple', 'pen']); // \"pen,pineapple,apple,pen\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### JSONtoCSV \n\n将对象数组转换为仅包含指定的`columns`的逗号分隔值`(CSV)`字符串。\n\n使用 `Array.prototype.join(delimiter)` 合并`columns`中的所有名称以创建第一行。、\n\n使用 `Array.prototype.map()` 和 `Array.prototype.reduce()` 为每个对象创建一行，用空字符串替换不存在的值，只映射“列”中的值。\n\n使用` Array.prototype.join('\\n') `将所有行组合成一个字符串。\n忽略第三个参数 `delimiter`,使用默认分隔符 `,`。\n\n```js\nconst JSONtoCSV = (arr, columns, delimiter = ',') =\u003e\n  [\n    columns.join(delimiter),\n    ...arr.map(obj =\u003e\n      columns.reduce(\n        (acc, key) =\u003e `${acc}${!acc.length ? '' : delimiter}\"${!obj[key] ? '' : obj[key]}\"`,\n        ''\n      )\n    )\n  ].join('\\n');\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nJSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b']); // 'a,b\\n\"1\",\"2\"\\n\"3\",\"4\"\\n\"6\",\"\"\\n\"\",\"7\"'\nJSONtoCSV([{ a: 1, b: 2 }, { a: 3, b: 4, c: 5 }, { a: 6 }, { b: 7 }], ['a', 'b'], ';'); // 'a;b\\n\"1\";\"2\"\\n\"3\";\"4\"\\n\"6\";\"\"\\n\"\";\"7\"'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### last\n\n返回数组中最后一个元素。\n\n使用 `arr.length - 1` 来计算给定数组最后一个元素的索引，然后返回它。\n\n```js\nconst last = arr =\u003e arr[arr.length - 1];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlast([1, 2, 3]); // 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### longestItem\n\n\n获取任意数量的可迭代对象或具有 `length` 属性的对象，并返回其中最长的一个。\n\n如果多个对象具有相同的长度，则返回第一个对象。\n如果没有提供参数，则返回“undefined”。\n\n使用` Array.prototype.reduce() `，比较对象的` length `以找到最长的对象。\n\n\n```js\nconst longestItem = (...vals) =\u003e vals.reduce((a, x) =\u003e (x.length \u003e a.length ? x : a));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlongestItem('this', 'is', 'a', 'testcase'); // 'testcase'\nlongestItem(...['a', 'ab', 'abc']); // 'abc'\nlongestItem(...['a', 'ab', 'abc'], 'abcd'); // 'abcd'\nlongestItem([1, 2, 3], [1, 2], [1, 2, 3, 4, 5]); // [1, 2, 3, 4, 5]\nlongestItem([1, 2, 3], 'foobar'); // 'foobar'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### mapObject \n\n使用函数将数组的值映射到对象，其中键值对由作为键的原始值和映射的值组成。\n\n使用匿名内部函数作用域声明未定义的内存空间，使用闭包存储返回值。使用一个新的 `Array` 来存储数组，其中包含函数在其数据集上的映射，并使用逗号操作符返回第二个步骤，而不需要从一个上下文移动到另一个上下文(由于闭包和操作顺序)。\n\n```js\nconst mapObject = (arr, fn) =\u003e\n  (a =\u003e (\n    (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) =\u003e ((acc[val] = a[1][ind]), acc), {})\n  ))();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst squareIt = arr =\u003e mapObject(arr, a =\u003e a * a);\nsquareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 }\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### maxN\n\n返回给定数组中前 `n` 大的元素。\n如果 `n` 比给定的数组长度还要大，返回原始数组（按降序排列）。\n\n使用 `Array.prototype.sort()` 结合展开操作符 (`...`) 创建一个数组的浅克隆，并按照降序排序。\n使用 `Array.prototype.slice()` 获取指定数量的元素。\n忽略第二个参数, `n`, 返回一个单元素数组。\n\n```js\nconst maxN = (arr, n = 1) =\u003e [...arr].sort((a, b) =\u003e b - a).slice(0, n);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nmaxN([1, 2, 3]); // [3]\nmaxN([1, 2, 3], 2); // [3,2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### minN\n\n返回给定数组中前 `n` 小的元素。\n如果 `n` 比给定的数组长度还要大，返回原始数组（按升序排列）。\n\n使用 `Array.prototype.sort()` 结合展开操作符 (`...`) 创建一个数组的浅克隆，并按照升序排序。\n使用 `Array.prototype.slice()` 获取指定数量的元素。\n忽略第二个参数, `n`, 返回一个单元素数组。\n\n```js\nconst minN = (arr, n = 1) =\u003e [...arr].sort((a, b) =\u003e a - b).slice(0, n);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nminN([1, 2, 3]); // [1]\nminN([1, 2, 3], 2); // [1,2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### none\n\n如果对集合中所有的元素执行判定函数全部都返回`false`，那么函数返回`true`，否则返回`false`。\n\n基于`fn`使用`Array.prototype.some()`来测试是否集合中有任意一个元素返回`true`。\n\n忽略第二个参数，`fn`，使用`Boolean`作为默认值。\n\n```js\nconst none = (arr, fn = Boolean) =\u003e !arr.some(fn);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nnone([0, 1, 3, 0], x =\u003e x == 2); // true\nnone([0, 0, 0]); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### nthElement\n\n返回数组中第`n`个元素(`n`可以是负数)。\n\n使用`Array.prototype.slice()`获得在首位包含第`n`个元素的数组。\n\n如果下标越界，返回`undefined`。\n\n如果没有第二个参数，`n`，返回数组中第一个元素。\n\n```js\nconst nthElement = (arr, n = 0) =\u003e (n === -1 ? arr.slice(n) : arr.slice(n, n + 1))[0];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nnthElement(['a', 'b', 'c'], 1); // 'b'\nnthElement(['a', 'b', 'b'], -3); // 'a'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### offset\n\n将指定数量的元素移动到数组的末尾。\n\n使用 `Array.prototype.slice()` 两次来获取指定索引后面的元素和前面的元素。\n\n使用扩展操作符(`...`)将两个数组合并成一个数组。\n\n如果`offset`是负，元素将被从末尾移动到开始。\n```js\nconst offset = (arr, offset) =\u003e [...arr.slice(offset), ...arr.slice(0, offset)];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\noffset([1, 2, 3, 4, 5], 2); // [3, 4, 5, 1, 2]\noffset([1, 2, 3, 4, 5], -2); // [4, 5, 1, 2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### partition\n\n根据提供的函数对每个元素的真实性，将元素分组为两个数组。\n\n使用`Array.prototype.reduce()`创建一个由两个数组组成的数组。\n\n使用`Array.prototype.push()`将执行`fn`返回`true`的元素添加到第一个数组，执行`fn`返回`false`的元素添加到第二个数组。\n\n```js\nconst partition = (arr, fn) =\u003e\n  arr.reduce(\n    (acc, val, i, arr) =\u003e {\n      acc[fn(val, i, arr) ? 0 : 1].push(val);\n      return acc;\n    },\n    [[], []]\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst users = [{ user: 'barney', age: 36, active: false }, { user: 'fred', age: 40, active: true }];\npartition(users, o =\u003e o.active); // [[{ 'user': 'fred',    'age': 40, 'active': true }],[{ 'user': 'barney',  'age': 36, 'active': false }]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### permutations ![advanced](/advanced.svg)\n\n生成数组元素的所有排列(包括重复元素)\n\n使用递归。\n\n对于给定数组中的每个元素，为其其余元素创建所有部分排列。\n\n使用`Array.prototype.map()`组合每个元素的部分排列，然后使用`Array.prototype.reduce()`组合一个数组中的所有排列。\n\n基本情况是数组`length` 等于 `2` 或 `1`。\n\n```js\nconst permutations = arr =\u003e {\n  if (arr.length \u003c= 2) return arr.length === 2 ? [arr, [arr[1], arr[0]]] : arr;\n  return arr.reduce(\n    (acc, item, i) =\u003e\n      acc.concat(\n        permutations([...arr.slice(0, i), ...arr.slice(i + 1)]).map(val =\u003e [item, ...val])\n      ),\n    []\n  );\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\npermutations([1, 33, 5]); // [ [ 1, 33, 5 ], [ 1, 5, 33 ], [ 33, 1, 5 ], [ 33, 5, 1 ], [ 5, 1, 33 ], [ 5, 33, 1 ] ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### pull\n\n修改原始数组以过滤掉指定的值。\n\n使用`Array.prototype.filter()` 和 `Array.prototype.includes()`将不需要过滤的值提取出来。\n\n使用`Array.prototype。length = 0 `通过将数组的长度重置为`0`来改变数组中传递的值，并使用` array .prototype.push() `仅用提取的值重新填充数组。\n\n```js\nconst pull = (arr, ...args) =\u003e {\n  let argState = Array.isArray(args[0]) ? args[0] : args;\n  let pulled = arr.filter((v, i) =\u003e !argState.includes(v));\n  arr.length = 0;\n  pulled.forEach(v =\u003e arr.push(v));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlet myArray = ['a', 'b', 'c', 'a', 'b', 'c'];\npull(myArray, 'a', 'c'); // myArray = [ 'b', 'b' ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### pullAtIndex \n\n修改原始数组，以过滤指定索引处的值。\n\n使用`Array.prototype.filter()` 和 `Array.prototype.includes()`将不需要过滤的值提取出来。\n\n使用`Array.prototype。length = 0 `通过将数组的长度重置为`0`来改变数组中传递的值，并使用` array .prototype.push() `仅用提取的值重新填充数组。\n\n```js\nconst pullAtIndex = (arr, pullArr) =\u003e {\n  let removed = [];\n  let pulled = arr\n    .map((v, i) =\u003e (pullArr.includes(i) ? removed.push(v) : v))\n    .filter((v, i) =\u003e !pullArr.includes(i));\n  arr.length = 0;\n  pulled.forEach(v =\u003e arr.push(v));\n  return removed;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlet myArray = ['a', 'b', 'c', 'd'];\nlet pulled = pullAtIndex(myArray, [1, 3]); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### pullAtValue \n\n修改原始数组，以过滤掉指定的值。返回移除后的元素。\n\n使用`Array.prototype.filter()` 和 `Array.prototype.includes()`将不需要过滤的值提取出来。\n\n使用`Array.prototype。length = 0 `通过将数组的长度重置为`0`来改变数组中传递的值，并使用` array .prototype.push() `仅用提取的值重新填充数组。\n\n使用`Array.prototype.push() `跟踪拉取出来的值。\n\n\n```js\nconst pullAtValue = (arr, pullArr) =\u003e {\n  let removed = [],\n    pushToRemove = arr.forEach((v, i) =\u003e (pullArr.includes(v) ? removed.push(v) : v)),\n    mutateTo = arr.filter((v, i) =\u003e !pullArr.includes(v));\n  arr.length = 0;\n  mutateTo.forEach(v =\u003e arr.push(v));\n  return removed;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nlet myArray = ['a', 'b', 'c', 'd'];\nlet pulled = pullAtValue(myArray, ['b', 'd']); // myArray = [ 'a', 'c' ] , pulled = [ 'b', 'd' ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n\n### reducedFilter\n\n根据一个条件过滤对象数组，同时过滤掉未指定的键。\n\n使用`Array.prototype.filter()`根据判定函数`fn`对数组进行过滤，返回条件返回`true`值的对象。\n\n在过滤后的数组的基础上，使用 `Array.prototype.map()` 返回使用 `Array.prototype.reduce()` 将不在参数`keys`中的属性过滤掉后的新对象。\n\n```js\nconst reducedFilter = (data, keys, fn) =\u003e\n  data.filter(fn).map(el =\u003e\n    keys.reduce((acc, key) =\u003e {\n      acc[key] = el[key];\n      return acc;\n    }, {})\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst data = [\n  {\n    id: 1,\n    name: 'john',\n    age: 24\n  },\n  {\n    id: 2,\n    name: 'mike',\n    age: 50\n  }\n];\n\nreducedFilter(data, ['id', 'name'], item =\u003e item.age \u003e 24); // [{ id: 2, name: 'mike'}]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### reduceSuccessive\n\n对累加器和数组中的每个元素应用一个函数(从左到右)，返回一个依次递减的值数组。\n\n使用`Array.prototype.reduce()` 将给定函数应用于给定数组，存储每个新结果。\n\n```js\nconst reduceSuccessive = (arr, fn, acc) =\u003e\n  arr.reduce((res, val, i, arr) =\u003e (res.push(fn(res.slice(-1)[0], val, i, arr)), res), [acc]);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nreduceSuccessive([1, 2, 3, 4, 5, 6], (acc, val) =\u003e acc + val, 0); // [0, 1, 3, 6, 10, 15, 21]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### reduceWhich\n\n将给定的函数设置比较规则后，返回数组的最小/最大值。\n\n结合使用`Array.prototype.reduce()` 和 `comparator`函数，以获取数组中的适当元素。\n\n你可以省略第二个参数， `comparator`，使用返回数组中最小元素的默认值。\n\n```js\nconst reduceWhich = (arr, comparator = (a, b) =\u003e a - b) =\u003e\n  arr.reduce((a, b) =\u003e (comparator(a, b) \u003e= 0 ? b : a));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nreduceWhich([1, 3, 2]); // 1\nreduceWhich([1, 3, 2], (a, b) =\u003e b - a); // 3\nreduceWhich(\n  [{ name: 'Tom', age: 12 }, { name: 'Jack', age: 18 }, { name: 'Lucy', age: 9 }],\n  (a, b) =\u003e a.age - b.age\n); // {name: \"Lucy\", age: 9}\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### reject\n\n接受一个判定函数和一个数组，像`Array.prototype.filter()`一样，但是仅仅当`pred(x) === false`才保留`x` 。\n\n```js\nconst reject = (pred, array) =\u003e array.filter((...args) =\u003e !pred(...args));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nreject(x =\u003e x % 2 === 0, [1, 2, 3, 4, 5]); // [1, 3, 5]\nreject(word =\u003e word.length \u003e 4, ['Apple', 'Pear', 'Kiwi', 'Banana']); // ['Pear', 'Kiwi']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### remove\n\nRemoves elements from an array for which the given function returns `false`.\n\nUse `Array.prototype.filter()` to find array elements that return truthy values and `Array.prototype.reduce()` to remove elements using `Array.prototype.splice()`.\nThe `func` is invoked with three arguments (`value, index, array`).\n\n```js\n\nconst remove = (arr, func) =\u003e\n  Array.isArray(arr)\n    ? arr.filter(func).reduce((acc, val) =\u003e {\n      arr.splice(arr.indexOf(val), 1);\n      return acc.concat(val);\n    }, [])\n    : [];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nremove([1, 2, 3, 4], n =\u003e n % 2 === 0); // [2, 4]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sample\n\nReturns a random element from an array.\n\nUse `Math.random()` to generate a random number, multiply it by `length` and round it off to the nearest whole number using `Math.floor()`.\nThis method also works with strings.\n\n```js\nconst sample = arr =\u003e arr[Math.floor(Math.random() * arr.length)];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsample([3, 7, 9, 11]); // 9\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sampleSize\n\nGets `n` random elements at unique keys from `array` up to the size of `array`.\n\nShuffle the array using the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle).\nUse `Array.prototype.slice()` to get the first `n` elements.\nOmit the second argument, `n` to get only one element at random from the array.\n\n```js\nconst sampleSize = ([...arr], n = 1) =\u003e {\n  let m = arr.length;\n  while (m) {\n    const i = Math.floor(Math.random() * m--);\n    [arr[m], arr[i]] = [arr[i], arr[m]];\n  }\n  return arr.slice(0, n);\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsampleSize([1, 2, 3], 2); // [3,1]\nsampleSize([1, 2, 3], 4); // [2,3,1]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### shank\n\nHas the same functionality as [`Array.prototype.splice()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice), but returning a new array instead of mutating the original array.\n\nUse `Array.prototype.slice()` and `Array.prototype.concat()` to get a new array with the new contents after removing existing elements and/or adding new elements.\nOmit the second argument, `index`, to start at `0`.\nOmit the third argument, `delCount`, to remove `0` elements.\nOmit the fourth argument, `elements`, in order to not add any new elements.\n\n```js\nconst shank = (arr, index = 0, delCount = 0, ...elements) =\u003e\n  arr\n    .slice(0, index)\n    .concat(elements)\n    .concat(arr.slice(index + delCount));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst names = ['alpha', 'bravo', 'charlie'];\nconst namesAndDelta = shank(names, 1, 0, 'delta'); // [ 'alpha', 'delta', 'bravo', 'charlie' ]\nconst namesNoBravo = shank(names, 1, 1); // [ 'alpha', 'charlie' ]\nconsole.log(names); // ['alpha', 'bravo', 'charlie']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### shuffle\n\nRandomizes the order of the values of an array, returning a new array.\n\nUses the [Fisher-Yates algorithm](https://github.com/30-seconds/30-seconds-of-code#shuffle) to reorder the elements of the array.\n\n```js\nconst shuffle = ([...arr]) =\u003e {\n  let m = arr.length;\n  while (m) {\n    const i = Math.floor(Math.random() * m--);\n    [arr[m], arr[i]] = [arr[i], arr[m]];\n  }\n  return arr;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst foo = [1, 2, 3];\nshuffle(foo); // [2, 3, 1], foo = [1, 2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### similarity\n\nReturns an array of elements that appear in both arrays.\n\nUse `Array.prototype.filter()` to remove values that are not part of `values`, determined using `Array.prototype.includes()`.\n\n```js\nconst similarity = (arr, values) =\u003e arr.filter(v =\u003e values.includes(v));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsimilarity([1, 2, 3], [1, 2, 4]); // [1, 2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sortedIndex\n\nReturns the lowest index at which value should be inserted into array in order to maintain its sort order.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted.\n\n```js\nconst sortedIndex = (arr, n) =\u003e {\n  const isDescending = arr[0] \u003e arr[arr.length - 1];\n  const index = arr.findIndex(el =\u003e (isDescending ? n \u003e= el : n \u003c= el));\n  return index === -1 ? arr.length : index;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsortedIndex([5, 3, 2, 1], 4); // 1\nsortedIndex([30, 50], 40); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sortedIndexBy\n\nReturns the lowest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.findIndex()` to find the appropriate index where the element should be inserted, based on the iterator function `fn`.\n\n```js\nconst sortedIndexBy = (arr, n, fn) =\u003e {\n  const isDescending = fn(arr[0]) \u003e fn(arr[arr.length - 1]);\n  const val = fn(n);\n  const index = arr.findIndex(el =\u003e (isDescending ? val \u003e= fn(el) : val \u003c= fn(el)));\n  return index === -1 ? arr.length : index;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsortedIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o =\u003e o.x); // 0\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sortedLastIndex\n\nReturns the highest index at which value should be inserted into array in order to maintain its sort order.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted.\n\n```js\nconst sortedLastIndex = (arr, n) =\u003e {\n  const isDescending = arr[0] \u003e arr[arr.length - 1];\n  const index = arr.reverse().findIndex(el =\u003e (isDescending ? n \u003c= el : n \u003e= el));\n  return index === -1 ? 0 : arr.length - index;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsortedLastIndex([10, 20, 30, 30, 40], 30); // 4\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### sortedLastIndexBy\n\nReturns the highest index at which value should be inserted into array in order to maintain its sort order, based on a provided iterator function.\n\nCheck if the array is sorted in descending order (loosely).\nUse `Array.prototype.map()` to apply the iterator function to all elements of the array.\nUse `Array.prototype.reverse()` and `Array.prototype.findIndex()` to find the appropriate last index where the element should be inserted, based on the provided iterator function.\n\n```js\nconst sortedLastIndexBy = (arr, n, fn) =\u003e {\n  const isDescending = fn(arr[0]) \u003e fn(arr[arr.length - 1]);\n  const val = fn(n);\n  const index = arr\n    .map(fn)\n    .reverse()\n    .findIndex(el =\u003e (isDescending ? val \u003c= el : val \u003e= el));\n  return index === -1 ? 0 : arr.length - index;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsortedLastIndexBy([{ x: 4 }, { x: 5 }], { x: 4 }, o =\u003e o.x); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### stableSort ![advanced](/advanced.svg)\n\nPerforms stable sorting of an array, preserving the initial indexes of items when their values are the same.\nDoes not mutate the original array, but returns a new array instead.\n\nUse `Array.prototype.map()` to pair each element of the input array with its corresponding index.\nUse `Array.prototype.sort()` and a `compare` function to sort the list, preserving their initial order if the items compared are equal.\nUse `Array.prototype.map()` to convert back to the initial array items.\n\n```js\nconst stableSort = (arr, compare) =\u003e\n  arr\n    .map((item, index) =\u003e ({ item, index }))\n    .sort((a, b) =\u003e compare(a.item, b.item) || a.index - b.index)\n    .map(({ item }) =\u003e item);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];\nconst stable = stableSort(arr, () =\u003e 0); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### symmetricDifference\n\nReturns the symmetric difference between two arrays, without filtering out duplicate values.\n\nCreate a `Set` from each array, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.\n\n```js\nconst symmetricDifference = (a, b) =\u003e {\n  const sA = new Set(a),\n    sB = new Set(b);\n  return [...a.filter(x =\u003e !sB.has(x)), ...b.filter(x =\u003e !sA.has(x))];\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]\nsymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### symmetricDifferenceBy\n\nReturns the symmetric difference between two arrays, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying `fn` to each array's elements, then use `Array.prototype.filter()` on each of them to only keep values not contained in the other.\n\n```js\nconst symmetricDifferenceBy = (a, b, fn) =\u003e {\n  const sA = new Set(a.map(v =\u003e fn(v))),\n    sB = new Set(b.map(v =\u003e fn(v)));\n  return [...a.filter(x =\u003e !sB.has(fn(x))), ...b.filter(x =\u003e !sA.has(fn(x)))];\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsymmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### symmetricDifferenceWith\n\nReturns the symmetric difference between two arrays, using a provided function as a comparator.\n\nUse `Array.prototype.filter()` and `Array.prototype.findIndex()` to find the appropriate values.\n\n```js\nconst symmetricDifferenceWith = (arr, val, comp) =\u003e [\n  ...arr.filter(a =\u003e val.findIndex(b =\u003e comp(a, b)) === -1),\n  ...val.filter(a =\u003e arr.findIndex(b =\u003e comp(a, b)) === -1)\n];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nsymmetricDifferenceWith(\n  [1, 1.2, 1.5, 3, 0],\n  [1.9, 3, 0, 3.9],\n  (a, b) =\u003e Math.round(a) === Math.round(b)\n); // [1, 1.2, 3.9]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### tail\n\nReturns all elements in an array except for the first one.\n\nReturn `Array.prototype.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array.\n\n```js\nconst tail = arr =\u003e (arr.length \u003e 1 ? arr.slice(1) : arr);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntail([1, 2, 3]); // [2,3]\ntail([1]); // [1]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### take\n\nReturns an array with n elements removed from the beginning.\n\nUse `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the beginning.\n\n```js\nconst take = (arr, n = 1) =\u003e arr.slice(0, n);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntake([1, 2, 3], 5); // [1, 2, 3]\ntake([1, 2, 3], 0); // []\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### takeRight\n\nReturns an array with n elements removed from the end.\n\nUse `Array.prototype.slice()` to create a slice of the array with `n` elements taken from the end.\n\n```js\nconst takeRight = (arr, n = 1) =\u003e arr.slice(arr.length - n, arr.length);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntakeRight([1, 2, 3], 2); // [ 2, 3 ]\ntakeRight([1, 2, 3]); // [3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### takeRightWhile\n\nRemoves elements from the end of an array until the passed function returns `true`. Returns the removed elements.\n\nLoop through the array, using a `Array.prototype.reduceRight()` and accumulating elements while the function returns falsy value.\n\n```js\nconst takeRightWhile = (arr, func) =\u003e\n  arr.reduceRight((acc, el) =\u003e (func(el) ? acc : [el, ...acc]), []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntakeRightWhile([1, 2, 3, 4], n =\u003e n \u003c 3); // [3, 4]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### takeWhile\n\nRemoves elements in an array until the passed function returns `true`. Returns the removed elements.\n\nLoop through the array, using a `for...of` loop over `Array.prototype.entries()` until the returned value from the function is `true`.\nReturn the removed elements, using `Array.prototype.slice()`.\n\n```js\nconst takeWhile = (arr, func) =\u003e {\n  for (const [i, val] of arr.entries()) if (func(val)) return arr.slice(0, i);\n  return arr;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntakeWhile([1, 2, 3, 4], n =\u003e n \u003e= 3); // [1, 2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### toHash\n\nReduces a given Array-like into a value hash (keyed data store).\n\nGiven an Iterable or Array-like structure, call `Array.prototype.reduce.call()` on the provided object to step over it and return an Object, keyed by the reference value.\n\n```js\nconst toHash = (object, key) =\u003e\n  Array.prototype.reduce.call(\n    object,\n    (acc, data, index) =\u003e ((acc[!key ? index : data[key]] = data), acc),\n    {}\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ntoHash([4, 3, 2, 1]); // { 0: 4, 1: 3, 2: 2, 3: 1 }\ntoHash([{ a: 'label' }], 'a'); // { label: { a: 'label' } }\n// A more in depth example:\nlet users = [{ id: 1, first: 'Jon' }, { id: 2, first: 'Joe' }, { id: 3, first: 'Moe' }];\nlet managers = [{ manager: 1, employees: [2, 3] }];\n// We use function here because we want a bindable reference, but a closure referencing the hash would work, too.\nmanagers.forEach(\n  manager =\u003e\n    (manager.employees = manager.employees.map(function(id) {\n      return this[id];\n    }, toHash(users, 'id')))\n);\nmanagers; // [ { manager:1, employees: [ { id: 2, first: \"Joe\" }, { id: 3, first: \"Moe\" } ] } ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### union\n\nReturns every element that exists in any of the two arrays once.\n\nCreate a `Set` with all values of `a` and `b` and convert to an array.\n\n```js\nconst union = (a, b) =\u003e Array.from(new Set([...a, ...b]));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nunion([1, 2, 3], [4, 3, 2]); // [1,2,3,4]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### unionBy\n\nReturns every element that exists in any of the two arrays once, after applying the provided function to each array element of both.\n\nCreate a `Set` by applying all `fn` to all values of `a`.\nCreate a `Set` from `a` and all elements in `b` whose value, after applying `fn` does not match a value in the previously created set.\nReturn the last set converted to an array.\n\n```js\nconst unionBy = (a, b, fn) =\u003e {\n  const s = new Set(a.map(fn));\n  return Array.from(new Set([...a, ...b.filter(x =\u003e !s.has(fn(x)))]));\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nunionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### unionWith\n\nReturns every element that exists in any of the two arrays once, using a provided comparator function.\n\nCreate a `Set` with all values of `a` and values in `b` for which the comparator finds no matches in `a`, using `Array.prototype.findIndex()`.\n\n```js\nconst unionWith = (a, b, comp) =\u003e\n  Array.from(new Set([...a, ...b.filter(x =\u003e a.findIndex(y =\u003e comp(x, y)) === -1)]));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nunionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) =\u003e Math.round(a) === Math.round(b)); // [1, 1.2, 1.5, 3, 0, 3.9]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### uniqueElements\n\nReturns all unique values of an array.\n\nUse ES6 `Set` and the `...rest` operator to discard all duplicated values.\n\n```js\nconst uniqueElements = arr =\u003e [...new Set(arr)];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nuniqueElements([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### uniqueElementsBy\n\nReturns all unique values of an array, based on a provided comparator function.\n\nUse `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the first unique occurence of each value, based on the comparator function, `fn`.\nThe comparator function takes two arguments: the values of the two elements being compared.\n\n```js\nconst uniqueElementsBy = (arr, fn) =\u003e\n  arr.reduce((acc, v) =\u003e {\n    if (!acc.some(x =\u003e fn(v, x))) acc.push(v);\n    return acc;\n  }, []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nuniqueElementsBy(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) =\u003e a.id == b.id\n); // [ { id: 0, value: 'a' }, { id: 1, value: 'b' }, { id: 2, value: 'c' } ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### uniqueElementsByRight\n\nReturns all unique values of an array, based on a provided comparator function.\n\nUse `Array.prototype.reduce()` and `Array.prototype.some()` for an array containing only the last unique occurence of each value, based on the comparator function, `fn`.\nThe comparator function takes two arguments: the values of the two elements being compared.\n\n```js\nconst uniqueElementsByRight = (arr, fn) =\u003e\n  arr.reduceRight((acc, v) =\u003e {\n    if (!acc.some(x =\u003e fn(v, x))) acc.push(v);\n    return acc;\n  }, []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nuniqueElementsByRight(\n  [\n    { id: 0, value: 'a' },\n    { id: 1, value: 'b' },\n    { id: 2, value: 'c' },\n    { id: 1, value: 'd' },\n    { id: 0, value: 'e' }\n  ],\n  (a, b) =\u003e a.id == b.id\n); // [ { id: 0, value: 'e' }, { id: 1, value: 'd' }, { id: 2, value: 'c' } ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### uniqueSymmetricDifference\n\nReturns the unique symmetric difference between two arrays, not containing duplicate values from either array.\n\nUse `Array.prototype.filter()` and `Array.prototype.includes()` on each array to remove values contained in the other, then create a `Set` from the results, removing duplicate values.\n\n```js\nconst uniqueSymmetricDifference = (a, b) =\u003e [\n  ...new Set([...a.filter(v =\u003e !b.includes(v)), ...b.filter(v =\u003e !a.includes(v))])\n];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nuniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]\nuniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### unzip\n\nCreates an array of arrays, ungrouping the elements in an array produced by [zip](#zip).\n\nUse `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.\nUse `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.\n\n```js\nconst unzip = arr =\u003e\n  arr.reduce(\n    (acc, val) =\u003e (val.forEach((v, i) =\u003e acc[i].push(v)), acc),\n    Array.from({\n      length: Math.max(...arr.map(x =\u003e x.length))\n    }).map(x =\u003e [])\n  );\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nunzip([['a', 1, true], ['b', 2, false]]); // [['a', 'b'], [1, 2], [true, false]]\nunzip([['a', 1, true], ['b', 2]]); // [['a', 'b'], [1, 2], [true]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### unzipWith ![advanced](/advanced.svg)\n\nCreates an array of elements, ungrouping the elements in an array produced by [zip](#zip) and applying the provided function.\n\nUse `Math.max.apply()` to get the longest subarray in the array, `Array.prototype.map()` to make each element an array.\nUse `Array.prototype.reduce()` and `Array.prototype.forEach()` to map grouped values to individual arrays.\nUse `Array.prototype.map()` and the spread operator (`...`) to apply `fn` to each individual group of elements.\n\n```js\nconst unzipWith = (arr, fn) =\u003e\n  arr\n    .reduce(\n      (acc, val) =\u003e (val.forEach((v, i) =\u003e acc[i].push(v)), acc),\n      Array.from({\n        length: Math.max(...arr.map(x =\u003e x.length))\n      }).map(x =\u003e [])\n    )\n    .map(val =\u003e fn(...val));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nunzipWith([[1, 10, 100], [2, 20, 200]], (...args) =\u003e args.reduce((acc, v) =\u003e acc + v, 0)); // [3, 30, 300]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### without\n\nFilters out the elements of an array, that have one of the specified values.\n\nUse `Array.prototype.filter()` to create an array excluding(using `!Array.includes()`) all given values.\n\n_(For a snippet that mutates the original array see [`pull`](#pull))_\n\n```js\nconst without = (arr, ...args) =\u003e arr.filter(v =\u003e !args.includes(v));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nwithout([2, 1, 2, 3], 1, 2); // [3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### xProd\n\nCreates a new array out of the two supplied by creating each possible pair from the arrays.\n\nUse `Array.prototype.reduce()`, `Array.prototype.map()` and `Array.prototype.concat()` to produce every possible pair from the elements of the two arrays and save them in an array.\n\n```js\nconst xProd = (a, b) =\u003e a.reduce((acc, x) =\u003e acc.concat(b.map(y =\u003e [x, y])), []);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nxProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### zip\n\nCreates an array of elements, grouped based on the position in the original arrays.\n\nUse `Math.max.apply()` to get the longest array in the arguments.\nCreates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.\nIf lengths of the argument-arrays vary, `undefined` is used where no value could be found.\n\n```js\nconst zip = (...arrays) =\u003e {\n  const maxLength = Math.max(...arrays.map(x =\u003e x.length));\n  return Array.from({ length: maxLength }).map((_, i) =\u003e {\n    return Array.from({ length: arrays.length }, (_, k) =\u003e arrays[k][i]);\n  });\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nzip(['a', 'b'], [1, 2], [true, false]); // [['a', 1, true], ['b', 2, false]]\nzip(['a'], [1, 2], [true, false]); // [['a', 1, true], [undefined, 2, false]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### zipObject\n\nGiven an array of valid property identifiers and an array of values, return an object associating the properties to the values.\n\nSince an object can have undefined values but not undefined property pointers, the array of properties is used to decide the structure of the resulting object using `Array.prototype.reduce()`.\n\n```js\nconst zipObject = (props, values) =\u003e\n  props.reduce((obj, prop, index) =\u003e ((obj[prop] = values[index]), obj), {});\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nzipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined}\nzipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2}\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### zipWith ![advanced](/advanced.svg)\n\nCreates an array of elements, grouped based on the position in the original arrays and using function as the last value to specify how grouped values should be combined.\n\nCheck if the last argument provided is a function.\nUse `Math.max()` to get the longest array in the arguments.\nCreates an array with that length as return value and use `Array.from()` with a map-function to create an array of grouped elements.\nIf lengths of the argument-arrays vary, `undefined` is used where no value could be found.\nThe function is invoked with the elements of each group `(...group)`.\n\n```js\nconst zipWith = (...array) =\u003e {\n  const fn = typeof array[array.length - 1] === 'function' ? array.pop() : undefined;\n  return Array.from(\n    { length: Math.max(...array.map(a =\u003e a.length)) },\n    (_, i) =\u003e (fn ? fn(...array.map(a =\u003e a[i])) : array.map(a =\u003e a[i]))\n  );\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nzipWith([1, 2], [10, 20], [100, 200], (a, b, c) =\u003e a + b + c); // [111,222]\nzipWith(\n  [1, 2, 3],\n  [10, 20],\n  [100, 200],\n  (a, b, c) =\u003e (a != null ? a : 'a') + (b != null ? b : 'b') + (c != null ? c : 'c')\n); // [111, 222, '3bc']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n\n---\n\n## 🌐 Browser\n\n### arrayToHtmlList\n\nConverts the given array elements into `\u003cli\u003e` tags and appends them to the list of the given id.\n\nUse `Array.prototype.map()`, `document.querySelector()`, and an anonymous inner closure to create a list of html tags.\n\n```js\nconst arrayToHtmlList = (arr, listID) =\u003e\n  (el =\u003e (\n    (el = document.querySelector('#' + listID)),\n    (el.innerHTML += arr.map(item =\u003e `\u003cli\u003e${item}\u003c/li\u003e`).join(''))\n  ))();\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\narrayToHtmlList(['item 1', 'item 2'], 'myListID');\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### bottomVisible\n\nReturns `true` if the bottom of the page is visible, `false` otherwise.\n\nUse `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible.\n\n```js\nconst bottomVisible = () =\u003e\n  document.documentElement.clientHeight + window.scrollY \u003e=\n  (document.documentElement.scrollHeight || document.documentElement.clientHeight);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nbottomVisible(); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### copyToClipboard ![advanced](/advanced.svg)\n\n⚠️ **NOTICE:** The same functionality can be easily implemented by using the new asynchronous Clipboard API, which is still experimental but should be used in the future instead of this snippet. Find out more about it [here](https://github.com/w3c/clipboard-apis/blob/master/explainer.adoc#writing-to-the-clipboard).\n\nCopy a string to the clipboard. \nOnly works as a result of user action (i.e. inside a `click` event listener).\n\nCreate a new `\u003ctextarea\u003e` element, fill it with the supplied data and add it to the HTML document.\nUse `Selection.getRangeAt()`to store the selected range (if any).\nUse `document.execCommand('copy')` to copy to the clipboard.\nRemove the `\u003ctextarea\u003e` element from the HTML document.\nFinally, use `Selection().addRange()` to recover the original selected range (if any).\n\n```js\nconst copyToClipboard = str =\u003e {\n  const el = document.createElement('textarea');\n  el.value = str;\n  el.setAttribute('readonly', '');\n  el.style.position = 'absolute';\n  el.style.left = '-9999px';\n  document.body.appendChild(el);\n  const selected =\n    document.getSelection().rangeCount \u003e 0 ? document.getSelection().getRangeAt(0) : false;\n  el.select();\n  document.execCommand('copy');\n  document.body.removeChild(el);\n  if (selected) {\n    document.getSelection().removeAllRanges();\n    document.getSelection().addRange(selected);\n  }\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncopyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### counter ![advanced](/advanced.svg)\n\nCreates a counter with the specified range, step and duration for the specified selector.\n\nCheck if `step` has the proper sign and change it accordingly.\nUse `setInterval()` in combination with `Math.abs()` and `Math.floor()` to calculate the time between each new text draw.\nUse `document.querySelector().innerHTML` to update the value of the selected element.\nOmit the fourth parameter, `step`, to use a default step of `1`.\nOmit the fifth parameter, `duration`, to use a default duration of `2000`ms.\n\n```js\nconst counter = (selector, start, end, step = 1, duration = 2000) =\u003e {\n  let current = start,\n    _step = (end - start) * step \u003c 0 ? -step : step,\n    timer = setInterval(() =\u003e {\n      current += _step;\n      document.querySelector(selector).innerHTML = current;\n      if (current \u003e= end) document.querySelector(selector).innerHTML = end;\n      if (current \u003e= end) clearInterval(timer);\n    }, Math.abs(Math.floor(duration / (end - start))));\n  return timer;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncounter('#my-id', 1, 1000, 5, 2000); // Creates a 2-second timer for the element with id=\"my-id\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### createElement\n\nCreates an element from a string (without appending it to the document). \nIf the given string contains multiple elements, only the first one will be returned.\n\nUse `document.createElement()` to create a new element.\nSet its `innerHTML` to the string supplied as the argument. \nUse `ParentNode.firstElementChild` to return the element version of the string.\n\n```js\nconst createElement = str =\u003e {\n  const el = document.createElement('div');\n  el.innerHTML = str;\n  return el.firstElementChild;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst el = createElement(\n  `\u003cdiv class=\"container\"\u003e\n    \u003cp\u003eHello!\u003c/p\u003e\n  \u003c/div\u003e`\n);\nconsole.log(el.className); // 'container'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### createEventHub ![advanced](/advanced.svg)\n\nCreates a pub/sub ([publish–subscribe](https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern)) event hub with `emit`, `on`, and `off` methods.\n\nUse `Object.create(null)` to create an empty `hub` object that does not inherit properties from `Object.prototype`.\nFor `emit`, resolve the array of handlers based on the `event` argument and then run each one with `Array.prototype.forEach()` by passing in the data as an argument.\nFor `on`, create an array for the event if it does not yet exist, then use `Array.prototype.push()` to add the handler\nto the array.\nFor `off`, use `Array.prototype.findIndex()` to find the index of the handler in the event array and remove it using `Array.prototype.splice()`.\n\n```js\nconst createEventHub = () =\u003e ({\n  hub: Object.create(null),\n  emit(event, data) {\n    (this.hub[event] || []).forEach(handler =\u003e handler(data));\n  },\n  on(event, handler) {\n    if (!this.hub[event]) this.hub[event] = [];\n    this.hub[event].push(handler);\n  },\n  off(event, handler) {\n    const i = (this.hub[event] || []).findIndex(h =\u003e h === handler);\n    if (i \u003e -1) this.hub[event].splice(i, 1);\n  }\n});\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst handler = data =\u003e console.log(data);\nconst hub = createEventHub();\nlet increment = 0;\n\n// Subscribe: listen for different types of events\nhub.on('message', handler);\nhub.on('message', () =\u003e console.log('Message event fired'));\nhub.on('increment', () =\u003e increment++);\n\n// Publish: emit events to invoke all handlers subscribed to them, passing the data to them as an argument\nhub.emit('message', 'hello world'); // logs 'hello world' and 'Message event fired'\nhub.emit('message', { hello: 'world' }); // logs the object and 'Message event fired'\nhub.emit('increment'); // `increment` variable is now 1\n\n// Unsubscribe: stop a specific handler from listening to the 'message' event\nhub.off('message', handler);\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### currentURL\n\nReturns the current URL.\n\nUse `window.location.href` to get current URL.\n\n```js\nconst currentURL = () =\u003e window.location.href;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ncurrentURL(); // 'https://google.com'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### detectDeviceType\n\nDetects wether the website is being opened in a mobile device or a desktop/laptop.\n\nUse a regular expression to test the `navigator.userAgent` property to figure out if the device is a mobile device or a desktop/laptop.\n\n```js\nconst detectDeviceType = () =\u003e\n  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)\n    ? 'Mobile'\n    : 'Desktop';\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ndetectDeviceType(); // \"Mobile\" or \"Desktop\"\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### elementContains\n\nReturns `true` if the `parent` element contains the `child` element, `false` otherwise.\n\nCheck that `parent` is not the same element as `child`, use `parent.contains(child)` to check if the `parent` element contains the `child` element.\n\n```js\nconst elementContains = (parent, child) =\u003e parent !== child \u0026\u0026 parent.contains(child);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nelementContains(document.querySelector('head'), document.querySelector('title')); // true\nelementContains(document.querySelector('body'), document.querySelector('body')); // false\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### elementIsVisibleInViewport ![advanced](/advanced.svg)\n\nReturns `true` if the element specified is visible in the viewport, `false` otherwise.\n\nUse `Element.getBoundingClientRect()` and the `window.inner(Width|Height)` values\nto determine if a given element is visible in the viewport.\nOmit the second argument to determine if the element is entirely visible, or specify `true` to determine if\nit is partially visible.\n\n```js\nconst elementIsVisibleInViewport = (el, partiallyVisible = false) =\u003e {\n  const { top, left, bottom, right } = el.getBoundingClientRect();\n  const { innerHeight, innerWidth } = window;\n  return partiallyVisible\n    ? ((top \u003e 0 \u0026\u0026 top \u003c innerHeight) || (bottom \u003e 0 \u0026\u0026 bottom \u003c innerHeight)) \u0026\u0026\n        ((left \u003e 0 \u0026\u0026 left \u003c innerWidth) || (right \u003e 0 \u0026\u0026 right \u003c innerWidth))\n    : top \u003e= 0 \u0026\u0026 left \u003e= 0 \u0026\u0026 bottom \u003c= innerHeight \u0026\u0026 right \u003c= innerWidth;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\n// e.g. 100x100 viewport and a 10x10px element at position {top: -1, left: 0, bottom: 9, right: 10}\nelementIsVisibleInViewport(el); // false - (not fully visible)\nelementIsVisibleInViewport(el, true); // true - (partially visible)\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### getImages\n\nFetches all images from within an element and puts them into an array\n\nUse `Element.prototype.getElementsByTagName()` to fetch all `\u003cimg\u003e` elements inside the provided element, `Array.prototype.map()` to map every `src` attribute of their respective `\u003cimg\u003e` element, then create a `Set` to eliminate duplicates and return the array.\n\n```js\nconst getImages = (el, includeDuplicates = false) =\u003e {\n  const images = [...el.getElementsByTagName('img')].map(img =\u003e img.getAttribute('src'));\n  return includeDuplicates ? images : [...new Set(images)];\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ngetImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...']\ngetImages(document, false); // ['image1.jpg', 'image2.png', '...']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### getScrollPosition\n\nReturns the scroll position of the current page.\n\nUse `pageXOffset` and `pageYOffset` if they are defined, otherwise `scrollLeft` and `scrollTop`.\nYou can omit `el` to use a default value of `window`.\n\n```js\nconst getScrollPosition = (el = window) =\u003e ({\n  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,\n  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop\n});\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ngetScrollPosition(); // {x: 0, y: 200}\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### getStyle\n\nReturns the value of a CSS rule for the specified element.\n\nUse `Window.getComputedStyle()` to get the value of the CSS rule for the specified element.\n\n```js\nconst getStyle = (el, ruleName) =\u003e getComputedStyle(el)[ruleName];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ngetStyle(document.querySelector('p'), 'font-size'); // '16px'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### hasClass\n\nReturns `true` if the element has the specified class, `false` otherwise.\n\nUse `element.classList.contains()` to check if the element has the specified class.\n\n```js\nconst hasClass = (el, className) =\u003e el.classList.contains(className);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nhasClass(document.querySelector('p.special'), 'special'); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### hashBrowser ![advanced](/advanced.svg)\n\nCreates a hash for a value using the [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm. Returns a promise.\n\nUse the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to create a hash for the given value.\n\n```js\nconst hashBrowser = val =\u003e\n  crypto.subtle.digest('SHA-256', new TextEncoder('utf-8').encode(val)).then(h =\u003e {\n    let hexes = [],\n      view = new DataView(h);\n    for (let i = 0; i \u003c view.byteLength; i += 4)\n      hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));\n    return hexes.join('');\n  });\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nhashBrowser(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(console.log); // '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### hide\n\nHides all the elements specified.\n\nUse `NodeList.prototype.forEach()` to apply `display: none` to each element specified.\n\n```js\nconst hide = (...el) =\u003e [...el].forEach(e =\u003e (e.style.display = 'none'));\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nhide(document.querySelectorAll('img')); // Hides all \u003cimg\u003e elements on the page\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### httpsRedirect\n\nRedirects the page to HTTPS if its currently in HTTP. Also, pressing the back button doesn't take it back to the HTTP page as its replaced in the history.\n\nUse `location.protocol` to get the protocol currently being used. If it's not HTTPS, use `location.replace()` to replace the existing page with the HTTPS version of the page. Use `location.href` to get the full address, split it with `String.prototype.split()` and remove the protocol part of the URL.\n\n```js\nconst httpsRedirect = () =\u003e {\n  if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nhttpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### insertAfter\n\nInserts an HTML string after the end of the specified element.\n\nUse `el.insertAdjacentHTML()` with a position of `'afterend'` to parse `htmlString` and insert it after the end of `el`.\n\n```js\nconst insertAfter = (el, htmlString) =\u003e el.insertAdjacentHTML('afterend', htmlString);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninsertAfter(document.getElementById('myId'), '\u003cp\u003eafter\u003c/p\u003e'); // \u003cdiv id=\"myId\"\u003e...\u003c/div\u003e \u003cp\u003eafter\u003c/p\u003e\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### insertBefore\n\nInserts an HTML string before the start of the specified element.\n\nUse `el.insertAdjacentHTML()` with a position of `'beforebegin'` to parse `htmlString` and insert it before the start of `el`.\n\n```js\nconst insertBefore = (el, htmlString) =\u003e el.insertAdjacentHTML('beforebegin', htmlString);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\ninsertBefore(document.getElementById('myId'), '\u003cp\u003ebefore\u003c/p\u003e'); // \u003cp\u003ebefore\u003c/p\u003e \u003cdiv id=\"myId\"\u003e...\u003c/div\u003e\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### isBrowserTabFocused\n\nReturns `true` if the browser tab of the page is focused, `false` otherwise.\n\nUse the `Document.hidden` property, introduced by the Page Visibility API to check if the browser tab of the page is visible or hidden.\n\n```js\nconst isBrowserTabFocused = () =\u003e !document.hidden;\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nisBrowserTabFocused(); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### nodeListToArray\n\nConverts a `NodeList` to an array.\n\nUse spread operator inside new array to convert a `NodeList` to an array.\n\n```js\nconst nodeListToArray = nodeList =\u003e [...nodeList];\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nnodeListToArray(document.childNodes); // [ \u003c!DOCTYPE html\u003e, html ]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### observeMutations ![advanced](/advanced.svg)\n\nReturns a new MutationObserver and runs the provided callback for each mutation on the specified element.\n\nUse a [`MutationObserver`](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver) to observe mutations on the given element.\nUse `Array.prototype.forEach()` to run the callback for each mutation that is observed.\nOmit the third argument, `options`, to use the default [options](https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver#MutationObserverInit) (all `true`).\n\n```js\nconst observeMutations = (element, callback, options) =\u003e {\n  const observer = new MutationObserver(mutations =\u003e mutations.forEach(m =\u003e callback(m)));\n  observer.observe(\n    element,\n    Object.assign(\n      {\n        childList: true,\n        attributes: true,\n        attributeOldValue: true,\n        characterData: true,\n        characterDataOldValue: true,\n        subtree: true\n      },\n      options\n    )\n  );\n  return observer;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst obs = observeMutations(document, console.log); // Logs all mutations that happen on the page\nobs.disconnect(); // Disconnects the observer and stops logging mutations on the page\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### off\n\nRemoves an event listener from an element.\n\nUse `EventTarget.removeEventListener()` to remove an event listener from an element. \nOmit the fourth argument `opts` to use `false` or specify it based on the options used when the event listener was added.\n\n```js\nconst off = (el, evt, fn, opts = false) =\u003e el.removeEventListener(evt, fn, opts);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst fn = () =\u003e console.log('!');\ndocument.body.addEventListener('click', fn);\noff(document.body, 'click', fn); // no longer logs '!' upon clicking on the page\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### on\n\nAdds an event listener to an element with the ability to use event delegation.\n\nUse `EventTarget.addEventListener()` to add an event listener to an element. If there is a `target` property supplied to the options object, ensure the event target matches the target specified and then invoke the callback by supplying the correct `this` context.\nReturns a reference to the custom delegator function, in order to be possible to use with [`off`](#off).\nOmit `opts` to default to non-delegation behavior and event bubbling.\n\n```js\nconst on = (el, evt, fn, opts = {}) =\u003e {\n  const delegatorFn = e =\u003e e.target.matches(opts.target) \u0026\u0026 fn.call(e.target, e);\n  el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false);\n  if (opts.target) return delegatorFn;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst fn = () =\u003e console.log('!');\non(document.body, 'click', fn); // logs '!' upon clicking the body\non(document.body, 'click', fn, { target: 'p' }); // logs '!' upon clicking a `p` element child of the body\non(document.body, 'click', fn, { options: true }); // use capturing instead of bubbling\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### onUserInputChange ![advanced](/advanced.svg)\n\nRun the callback whenever the user input type changes (`mouse` or `touch`). Useful for enabling/disabling code depending on the input device. This process is dynamic and works with hybrid devices (e.g. touchscreen laptops).\n\nUse two event listeners. Assume `mouse` input initially and bind a `touchstart` event listener to the document. \nOn `touchstart`, add a `mousemove` event listener to listen for two consecutive `mousemove` events firing within 20ms, using `performance.now()`.\nRun the callback with the input type as an argument in either of these situations.\n\n```js\nconst onUserInputChange = callback =\u003e {\n  let type = 'mouse',\n    lastTime = 0;\n  const mousemoveHandler = () =\u003e {\n    const now = performance.now();\n    if (now - lastTime \u003c 20)\n      (type = 'mouse'), callback(type), document.removeEventListener('mousemove', mousemoveHandler);\n    lastTime = now;\n  };\n  document.addEventListener('touchstart', () =\u003e {\n    if (type === 'touch') return;\n    (type = 'touch'), callback(type), document.addEventListener('mousemove', mousemoveHandler);\n  });\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nonUserInputChange(type =\u003e {\n  console.log('The user is now using', type, 'as an input method.');\n});\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### prefix\n\nReturns the prefixed version (if necessary) of a CSS property that the browser supports.\n\nUse `Array.prototype.findIndex()` on an array of vendor prefix strings to test if `document.body` has one of them defined in its `CSSStyleDeclaration` object, otherwise return `null`.\nUse `String.prototype.charAt()` and `String.prototype.toUpperCase()` to capitalize the property, which will be appended to the vendor prefix string.\n\n```js\nconst prefix = prop =\u003e {\n  const capitalizedProp = prop.charAt(0).toUpperCase() + prop.slice(1);\n  const prefixes = ['', 'webkit', 'moz', 'ms', 'o'];\n  const i = prefixes.findIndex(\n    prefix =\u003e typeof document.body.style[prefix ? prefix + capitalizedProp : prop] !== 'undefined'\n  );\n  return i !== -1 ? (i === 0 ? prop : prefixes[i] + capitalizedProp) : null;\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nprefix('appearance'); // 'appearance' on a supported browser, otherwise 'webkitAppearance', 'mozAppearance', 'msAppearance' or 'oAppearance'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### recordAnimationFrames\n\nInvokes the provided callback on each animation frame.\n\nUse recursion. \nProvided that `running` is `true`, continue invoking `window.requestAnimationFrame()` which invokes the provided callback. \nReturn an object with two methods `start` and `stop` to allow manual control of the recording. \nOmit the second argument, `autoStart`, to implicitly call `start` when the function is invoked.\n\n```js\nconst recordAnimationFrames = (callback, autoStart = true) =\u003e {\n  let running = true,\n    raf;\n  const stop = () =\u003e {\n    running = false;\n    cancelAnimationFrame(raf);\n  };\n  const start = () =\u003e {\n    running = true;\n    run();\n  };\n  const run = () =\u003e {\n    raf = requestAnimationFrame(() =\u003e {\n      callback();\n      if (running) run();\n    });\n  };\n  if (autoStart) start();\n  return { start, stop };\n};\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nconst cb = () =\u003e console.log('Animation frame fired');\nconst recorder = recordAnimationFrames(cb); // logs 'Animation frame fired' on each animation frame\nrecorder.stop(); // stops logging\nrecorder.start(); // starts again\nconst recorder2 = recordAnimationFrames(cb, false); // `start` needs to be explicitly called to begin recording frames\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### redirect\n\nRedirects to a specified URL.\n\nUse `window.location.href` or `window.location.replace()` to redirect to `url`.\nPass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`).\n\n```js\nconst redirect = (url, asLink = true) =\u003e\n  asLink ? (window.location.href = url) : window.location.replace(url);\n```\n\n\u003cdetails\u003e\n\u003csummary\u003e示例\u003c/summary\u003e\n\n```js\nredirect('https://google.com');\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ 回到顶部](#目录)\n\n### runAsync ![advanced](/advanced.svg)\n\nRuns a function in a separate thread by using a [Web Worker](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers), allowing long running functions to not block the UI.\n\nCreate a new `Worker` using a `Blob` object URL, the contents of which should be the stringified version of the supplied function.\nImmediately post the return value of calling the ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flq782655835%2F30-seconds-of-code","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flq782655835%2F30-seconds-of-code","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flq782655835%2F30-seconds-of-code/lists"}