├── docs ├── CNAME ├── favicon.png └── clipboard.svg ├── test ├── head │ └── head.js ├── isEven │ ├── isEven.js │ └── isEven.test.js ├── isNull │ └── isNull.js ├── last │ └── last.js ├── take │ └── take.js ├── compact │ └── compact.js ├── initial │ └── initial.js ├── isArray │ └── isArray.js ├── byteSize │ └── byteSize.js ├── isObject │ └── isObject.js ├── negate │ └── negate.js ├── collatz │ ├── collatz.js │ └── collatz.test.js ├── currentURL │ └── currentURL.js ├── defer │ ├── defer.js │ └── defer.test.js ├── flip │ ├── flip.js │ └── flip.test.js ├── isBoolean │ └── isBoolean.js ├── isNumber │ └── isNumber.js ├── isString │ └── isString.js ├── isSymbol │ └── isSymbol.js ├── splitLines │ └── splitLines.js ├── tail │ └── tail.js ├── union │ └── union.js ├── call │ ├── call.js │ └── call.test.js ├── collectInto │ └── collectInto.js ├── digitize │ └── digitize.js ├── dropRight │ └── dropRight.js ├── findLast │ ├── findLast.js │ └── findLast.test.js ├── isFunction │ └── isFunction.js ├── spreadOver │ └── spreadOver.js ├── isLowerCase │ └── isLowerCase.js ├── isUpperCase │ └── isUpperCase.js ├── sample │ ├── sample.js │ └── sample.test.js ├── shallowClone │ └── shallowClone.js ├── show │ ├── show.js │ └── show.test.js ├── sleep │ ├── sleep.js │ └── sleep.test.js ├── sum │ └── sum.js ├── distance │ ├── distance.js │ └── distance.test.js ├── functionName │ └── functionName.js ├── getStyle │ ├── getStyle.js │ └── getStyle.test.js ├── hide │ ├── hide.js │ └── hide.test.js ├── maxN │ └── maxN.js ├── minN │ └── minN.js ├── reverseString │ └── reverseString.js ├── setStyle │ ├── setStyle.js │ └── setStyle.test.js ├── toDecimalMark │ └── toDecimalMark.js ├── without │ └── without.js ├── countVowels │ └── countVowels.js ├── hasClass │ ├── hasClass.js │ └── hasClass.test.js ├── isAbsoluteURL │ └── isAbsoluteURL.js ├── off │ ├── off.js │ └── off.test.js ├── cloneRegExp │ └── cloneRegExp.js ├── coalesce │ └── coalesce.js ├── coalesceFactory │ └── coalesceFactory.js ├── compose │ └── compose.js ├── everyNth │ └── everyNth.js ├── isDivisible │ └── isDivisible.js ├── isTravisCI │ └── isTravisCI.js ├── similarity │ └── similarity.js ├── takeRight │ └── takeRight.js ├── toggleClass │ └── toggleClass.js ├── words │ └── words.js ├── distinctValuesOfArray │ └── distinctValuesOfArray.js ├── escapeRegExp │ └── escapeRegExp.js ├── objectToPairs │ └── objectToPairs.js ├── removeVowels │ └── removeVowels.js ├── RGBToHex │ └── RGBToHex.js ├── average │ └── average.js ├── nthElement │ └── nthElement.js ├── round │ └── round.js ├── untildify │ └── untildify.js ├── longestItem │ └── longestItem.js ├── maxBy │ ├── maxBy.js │ └── maxBy.test.js ├── minBy │ ├── minBy.js │ └── minBy.test.js ├── powerset │ └── powerset.js ├── clampNumber │ └── clampNumber.js ├── isPrimitive │ └── isPrimitive.js ├── objectFromPairs │ └── objectFromPairs.js ├── pipeFunctions │ └── pipeFunctions.js ├── tomorrow │ └── tomorrow.js ├── validateNumber │ └── validateNumber.js ├── deepFlatten │ └── deepFlatten.js ├── filterNonUnique │ └── filterNonUnique.js ├── pick │ └── pick.js ├── randomNumberInRange │ └── randomNumberInRange.js ├── select │ └── select.js ├── transform │ └── transform.js ├── yesNo │ └── yesNo.js ├── difference │ └── difference.js ├── hammingDistance │ └── hammingDistance.js ├── initializeArrayWithValues │ └── initializeArrayWithValues.js ├── mask │ └── mask.js ├── capitalizeEveryWord │ └── capitalizeEveryWord.js ├── chainAsync │ └── chainAsync.js ├── countOccurrences │ └── countOccurrences.js ├── differenceWith │ └── differenceWith.js ├── forEachRight │ └── forEachRight.js ├── getType │ └── getType.js ├── intersection │ └── intersection.js ├── runPromisesInSeries │ └── runPromisesInSeries.js ├── serializeCookie │ └── serializeCookie.js ├── truthCheckCollection │ └── truthCheckCollection.js ├── randomIntegerInRange │ └── randomIntegerInRange.js ├── redirect │ ├── redirect.js │ └── redirect.test.js ├── sumBy │ ├── sumBy.js │ └── sumBy.test.js ├── curry │ └── curry.js ├── hasFlags │ ├── hasFlags.js │ └── hasFlags.test.js ├── isArrayLike │ └── isArrayLike.js ├── sortCharactersInString │ └── sortCharactersInString.js ├── zipObject │ └── zipObject.js ├── gcd │ └── gcd.js ├── initialize2DArray │ └── initialize2DArray.js ├── truncateString │ └── truncateString.js ├── dropElements │ └── dropElements.js ├── isValidJSON │ └── isValidJSON.js ├── toSafeInteger │ └── toSafeInteger.js ├── chunk │ └── chunk.js ├── mapKeys │ ├── mapKeys.js │ └── mapKeys.test.js ├── mapValues │ └── mapValues.js ├── percentile │ └── percentile.js ├── getDaysDiffBetweenDates │ └── getDaysDiffBetweenDates.js ├── invertKeyValues │ └── invertKeyValues.js ├── arrayToHtmlList │ └── arrayToHtmlList.js ├── averageBy │ └── averageBy.js ├── fibonacci │ └── fibonacci.js ├── httpsRedirect │ └── httpsRedirect.js ├── timeTaken │ └── timeTaken.js ├── capitalize │ └── capitalize.js ├── createElement │ └── createElement.js ├── extendHex │ └── extendHex.js ├── indexOfAll │ └── indexOfAll.js ├── lowercaseKeys │ └── lowercaseKeys.js ├── mapObject │ └── mapObject.js ├── decapitalize │ └── decapitalize.js ├── fibonacciCountUntilNum │ └── fibonacciCountUntilNum.js ├── isPromiseLike │ └── isPromiseLike.js ├── once │ ├── once.js │ └── once.test.js ├── README │ ├── README.js │ └── README.test.js ├── factorial │ └── factorial.js ├── promisify │ └── promisify.js ├── sumPower │ └── sumPower.js ├── isArmstrongNumber │ └── isArmstrongNumber.js ├── partition │ └── partition.js ├── randomIntArrayInRange │ └── randomIntArrayInRange.js ├── JSONToDate │ └── JSONToDate.js ├── isPrime │ └── isPrime.js ├── lcm │ └── lcm.js ├── reducedFilter │ └── reducedFilter.js ├── countBy │ ├── countBy.js │ └── countBy.test.js ├── detectDeviceType │ └── detectDeviceType.js ├── flatten │ └── flatten.js ├── inRange │ └── inRange.js ├── remove │ └── remove.js ├── toKebabCase │ └── toKebabCase.js ├── toSnakeCase │ └── toSnakeCase.js ├── bottomVisible │ └── bottomVisible.js ├── getURLParameters │ └── getURLParameters.js ├── palindrome │ └── palindrome.js ├── shuffle │ ├── shuffle.js │ └── shuffle.test.js ├── initializeArrayWithRange │ └── initializeArrayWithRange.js ├── median │ └── median.js ├── symmetricDifference │ └── symmetricDifference.js ├── groupBy │ └── groupBy.js ├── size │ └── size.js ├── escapeHTML │ └── escapeHTML.js ├── join │ └── join.js ├── randomHexColorCode │ └── randomHexColorCode.js ├── sdbm │ └── sdbm.js ├── speechSynthesis │ └── speechSynthesis.js ├── fromCamelCase │ └── fromCamelCase.js ├── functions │ └── functions.js ├── geometricProgression │ └── geometricProgression.js ├── getScrollPosition │ └── getScrollPosition.js ├── pull │ ├── pull.js │ └── pull.test.js ├── UUIDGeneratorBrowser │ └── UUIDGeneratorBrowser.js ├── parseCookie │ └── parseCookie.js ├── sampleSize │ └── sampleSize.js ├── merge │ ├── merge.js │ └── merge.test.js ├── quickSort │ └── quickSort.js ├── scrollToTop │ └── scrollToTop.js ├── sortedIndex │ └── sortedIndex.js ├── isSorted │ └── isSorted.js ├── zip │ └── zip.js ├── unescapeHTML │ └── unescapeHTML.js ├── memoize │ ├── memoize.js │ └── memoize.test.js ├── on │ ├── on.js │ └── on.test.js ├── httpDelete │ └── httpDelete.js ├── httpGet │ ├── httpGet.js │ └── httpGet.test.js ├── howManyTimes │ └── howManyTimes.js ├── pullAtIndex │ └── pullAtIndex.js ├── fibonacciUntilNum │ └── fibonacciUntilNum.js ├── toCamelCase │ └── toCamelCase.js ├── anagrams │ └── anagrams.js ├── cleanObj │ └── cleanObj.js ├── pullAtValue │ └── pullAtValue.js ├── pluralize │ └── pluralize.js ├── orderBy │ └── orderBy.js ├── primes │ └── primes.js ├── binarySearch │ └── binarySearch.js ├── luhnCheck │ └── luhnCheck.js ├── standardDeviation │ └── standardDeviation.js ├── httpPut │ ├── httpPut.js │ └── httpPut.test.js ├── httpPost │ ├── httpPost.js │ └── httpPost.test.js ├── toOrdinalSuffix │ └── toOrdinalSuffix.js ├── createEventHub │ └── createEventHub.js ├── runAsync │ ├── runAsync.js │ └── runAsync.test.js ├── formatDuration │ └── formatDuration.js ├── elementIsVisibleInViewport │ └── elementIsVisibleInViewport.js ├── prettyBytes │ └── prettyBytes.js ├── factors │ └── factors.test.js ├── colorize │ └── colorize.test.js └── solveRPN │ └── solveRPN.test.js ├── logo.png ├── .gitignore ├── snippets ├── head.zh.md ├── isNull.zh.md ├── last.zh.md ├── initial.zh.md ├── isArray.zh.md ├── isString.zh.md ├── isSymbol.zh.md ├── currentURL.zh.md ├── head.md ├── isEven.zh.md ├── isNumber.zh.md ├── union.zh.md ├── distance.zh.md ├── negate.zh.md ├── sum.zh.md ├── isDivisible.zh.md ├── isBoolean.zh.md ├── take.zh.md ├── isFunction.zh.md ├── tail.zh.md ├── currentURL.md ├── escapeRegExp.zh.md ├── digitize.zh.md ├── coalesce.zh.md ├── isArray.md ├── everyNth.zh.md ├── sample.zh.md ├── distinctValuesOfArray.zh.md ├── isString.md ├── round.zh.md ├── similarity.zh.md ├── findLast.zh.md ├── getStyle.zh.md ├── shallowClone.zh.md ├── spreadOver.zh.md ├── filterNonUnique.zh.md ├── isSymbol.md ├── last.md ├── objectFromPairs.zh.md ├── compact.zh.md ├── functionName.zh.md ├── initial.md ├── powerset.zh.md ├── reverseString.zh.md ├── byteSize.zh.md ├── objectToPairs.zh.md ├── randomNumberInRange.zh.md ├── show.zh.md ├── splitLines.zh.md ├── takeRight.zh.md ├── untildify.zh.md ├── average.zh.md ├── countOccurrences.zh.md ├── difference.zh.md ├── dropRight.zh.md ├── getType.zh.md ├── hasClass.zh.md ├── hide.zh.md ├── isLowerCase.zh.md ├── isNull.md ├── isNumber.md ├── isUpperCase.zh.md ├── toDecimalMark.zh.md ├── without.zh.md ├── escapeRegExp.md ├── intersection.zh.md ├── tomorrow.zh.md ├── distance.md ├── initializeArrayWithValues.zh.md ├── sum.md ├── clampNumber.zh.md ├── hammingDistance.zh.md ├── negate.md ├── randomIntegerInRange.zh.md ├── validateNumber.zh.md ├── RGBToHex.zh.md ├── deepFlatten.zh.md ├── isFunction.md ├── serializeCookie.zh.md ├── union.md ├── cloneRegExp.zh.md ├── isBoolean.md ├── truncateString.zh.md ├── capitalizeEveryWord.zh.md ├── isDivisible.md ├── pick.zh.md ├── coalesce.md ├── toggleClass.zh.md ├── everyNth.md ├── setStyle.zh.md ├── nthElement.zh.md ├── objectFromPairs.md ├── redirect.zh.md ├── tail.md ├── take.md ├── byteSize.md ├── distinctValuesOfArray.md ├── getDaysDiffBetweenDates.zh.md ├── isEven.md ├── percentile.zh.md ├── shallowClone.md ├── filterNonUnique.md ├── isAbsoluteURL.zh.md ├── sleep.zh.md ├── compact.md ├── initialize2DArray.zh.md ├── isPrime.zh.md ├── sortCharactersInString.zh.md ├── getStyle.md ├── maxN.zh.md ├── minN.zh.md ├── differenceWith.zh.md ├── dropElements.zh.md ├── factorial.zh.md ├── similarity.md ├── splitLines.md ├── toSafeInteger.zh.md ├── digitize.md ├── gcd.zh.md ├── hide.md ├── takeRight.md ├── arrayToHtmlList.zh.md ├── cloneRegExp.md ├── fibonacci.zh.md ├── functionName.md ├── getType.md ├── hasClass.md ├── invertKeyValues.zh.md ├── isLowerCase.md ├── randomNumberInRange.md ├── show.md ├── toDecimalMark.md ├── bottomVisible.zh.md ├── difference.md ├── isTravisCI.zh.md ├── isUpperCase.md ├── reverseString.md ├── truthCheckCollection.zh.md ├── compose.zh.md ├── findLast.md ├── forEachRight.zh.md ├── maxBy.zh.md ├── minBy.zh.md ├── objectToPairs.md ├── chunk.zh.md ├── countOccurrences.md ├── dropRight.md ├── median.zh.md ├── serializeCookie.md ├── symmetricDifference.zh.md ├── toggleClass.md ├── coalesceFactory.zh.md ├── detectDeviceType.zh.md ├── intersection.md ├── lcm.zh.md ├── powerset.md ├── sample.md ├── timeTaken.zh.md ├── untildify.md ├── JSONToFile.zh.md ├── yesNo.zh.md ├── average.md ├── randomIntegerInRange.md ├── round.md ├── curry.zh.md ├── isObject.zh.md ├── mapKeys.zh.md ├── sdbm.zh.md ├── capitalizeEveryWord.md ├── collectInto.zh.md ├── flip.zh.md ├── getDaysDiffBetweenDates.md ├── indexOfAll.zh.md ├── setStyle.md ├── words.zh.md ├── chainAsync.zh.md ├── isArrayLike.zh.md ├── pipeFunctions.zh.md ├── randomHexColorCode.zh.md ├── clampNumber.md ├── off.zh.md ├── tomorrow.md ├── zipObject.zh.md ├── deepFlatten.md ├── getScrollPosition.zh.md ├── isAbsoluteURL.md ├── sumBy.zh.md ├── RGBToHex.md ├── call.zh.md ├── isValidJSON.zh.md ├── randomIntArrayInRange.zh.md ├── without.md ├── capitalize.zh.md ├── redirect.md ├── sortCharactersInString.md ├── spreadOver.md ├── toSafeInteger.md ├── initializeArrayWithValues.md ├── runPromisesInSeries.zh.md ├── transform.zh.md ├── sleep.md ├── JSONToFile.md ├── arrayToHtmlList.md ├── inRange.zh.md ├── UUIDGeneratorBrowser.zh.md ├── decapitalize.zh.md ├── invertKeyValues.md ├── pick.md ├── remove.zh.md ├── shuffle.zh.md ├── sortedIndex.zh.md ├── UUIDGeneratorNode.zh.md ├── bottomVisible.md ├── differenceWith.md ├── extendHex.zh.md ├── hammingDistance.md ├── isPrimitive.zh.md ├── isTravisCI.md ├── scrollToTop.zh.md ├── truncateString.md ├── validateNumber.md ├── initialize2DArray.md ├── averageBy.zh.md ├── hasFlags.zh.md ├── mapObject.zh.md ├── sdbm.md ├── countBy.zh.md ├── getURLParameters.zh.md ├── lowercaseKeys.zh.md ├── nthElement.md ├── sumPower.zh.md ├── symmetricDifference.md ├── isPrime.md ├── mapValues.zh.md ├── maxBy.md ├── minBy.md ├── truthCheckCollection.md ├── UUIDGeneratorBrowser.md ├── flatten.zh.md ├── forEachRight.md ├── isValidJSON.md ├── palindrome.zh.md ├── select.zh.md └── yesNo.md ├── snippets_archive ├── collatz.zh.md ├── collatz.md ├── countVowels.zh.md ├── removeVowels.zh.md ├── fibonacciCountUntilNum.zh.md ├── countVowels.md ├── JSONToDate.zh.md ├── removeVowels.md ├── JSONToDate.md ├── isArmstrongNumber.zh.md └── fibonacciCountUntilNum.md ├── snippet-template.zh.md ├── dist └── NOTICE.zh.md └── snippet-template.md /docs/CNAME: -------------------------------------------------------------------------------- 1 | 30secondsofcode.org 2 | -------------------------------------------------------------------------------- /test/head/head.js: -------------------------------------------------------------------------------- 1 | module.exports = head = arr => arr[0]; -------------------------------------------------------------------------------- /test/isEven/isEven.js: -------------------------------------------------------------------------------- 1 | module.exports = isEven = num => num % 2 === 0; -------------------------------------------------------------------------------- /test/isNull/isNull.js: -------------------------------------------------------------------------------- 1 | module.exports = isNull = val => val === null; -------------------------------------------------------------------------------- /test/last/last.js: -------------------------------------------------------------------------------- 1 | module.exports = last = arr => arr[arr.length - 1]; -------------------------------------------------------------------------------- /test/take/take.js: -------------------------------------------------------------------------------- 1 | module.exports = take = (arr, n = 1) => arr.slice(0, n); -------------------------------------------------------------------------------- /test/compact/compact.js: -------------------------------------------------------------------------------- 1 | module.exports = compact = arr => arr.filter(Boolean); -------------------------------------------------------------------------------- /test/initial/initial.js: -------------------------------------------------------------------------------- 1 | module.exports = initial = arr => arr.slice(0, -1); -------------------------------------------------------------------------------- /test/isArray/isArray.js: -------------------------------------------------------------------------------- 1 | module.exports = isArray = val => Array.isArray(val); -------------------------------------------------------------------------------- /test/byteSize/byteSize.js: -------------------------------------------------------------------------------- 1 | module.exports = byteSize = str => new Blob([str]).size; -------------------------------------------------------------------------------- /test/isObject/isObject.js: -------------------------------------------------------------------------------- 1 | module.exports = isObject = obj => obj === Object(obj); -------------------------------------------------------------------------------- /test/negate/negate.js: -------------------------------------------------------------------------------- 1 | module.exports = negate = func => (...args) => !func(...args); -------------------------------------------------------------------------------- /logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinanf-boy/30-seconds-of-code/master/logo.png -------------------------------------------------------------------------------- /test/collatz/collatz.js: -------------------------------------------------------------------------------- 1 | module.exports = collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); -------------------------------------------------------------------------------- /test/currentURL/currentURL.js: -------------------------------------------------------------------------------- 1 | module.exports = currentURL = () => window.location.href; -------------------------------------------------------------------------------- /test/defer/defer.js: -------------------------------------------------------------------------------- 1 | module.exports = defer = (fn, ...args) => setTimeout(fn, 1, ...args); -------------------------------------------------------------------------------- /test/flip/flip.js: -------------------------------------------------------------------------------- 1 | module.exports = flip = fn => (...args) => fn(args.pop(), ...args); -------------------------------------------------------------------------------- /test/isBoolean/isBoolean.js: -------------------------------------------------------------------------------- 1 | module.exports = isBoolean = val => typeof val === 'boolean'; -------------------------------------------------------------------------------- /test/isNumber/isNumber.js: -------------------------------------------------------------------------------- 1 | module.exports = isNumber = val => typeof val === 'number'; -------------------------------------------------------------------------------- /test/isString/isString.js: -------------------------------------------------------------------------------- 1 | module.exports = isString = val => typeof val === 'string'; -------------------------------------------------------------------------------- /test/isSymbol/isSymbol.js: -------------------------------------------------------------------------------- 1 | module.exports = isSymbol = val => typeof val === 'symbol'; -------------------------------------------------------------------------------- /test/splitLines/splitLines.js: -------------------------------------------------------------------------------- 1 | module.exports = splitLines = str => str.split(/\r?\n/); -------------------------------------------------------------------------------- /test/tail/tail.js: -------------------------------------------------------------------------------- 1 | module.exports = tail = arr => (arr.length > 1 ? arr.slice(1) : arr); -------------------------------------------------------------------------------- /test/union/union.js: -------------------------------------------------------------------------------- 1 | module.exports = union = (a, b) => Array.from(new Set([...a, ...b])); -------------------------------------------------------------------------------- /test/call/call.js: -------------------------------------------------------------------------------- 1 | module.exports = call = (key, ...args) => context => context[key](...args); -------------------------------------------------------------------------------- /test/collectInto/collectInto.js: -------------------------------------------------------------------------------- 1 | module.exports = collectInto = fn => (...args) => fn(args); -------------------------------------------------------------------------------- /test/digitize/digitize.js: -------------------------------------------------------------------------------- 1 | module.exports = digitize = n => [...`${n}`].map(i => parseInt(i)); -------------------------------------------------------------------------------- /test/dropRight/dropRight.js: -------------------------------------------------------------------------------- 1 | module.exports = dropRight = (arr, n = 1) => arr.slice(0, -n); -------------------------------------------------------------------------------- /test/findLast/findLast.js: -------------------------------------------------------------------------------- 1 | module.exports = findLast = (arr, fn) => arr.filter(fn).slice(-1); -------------------------------------------------------------------------------- /test/isFunction/isFunction.js: -------------------------------------------------------------------------------- 1 | module.exports = isFunction = val => typeof val === 'function'; -------------------------------------------------------------------------------- /test/spreadOver/spreadOver.js: -------------------------------------------------------------------------------- 1 | module.exports = spreadOver = fn => argsArr => fn(...argsArr); -------------------------------------------------------------------------------- /test/isLowerCase/isLowerCase.js: -------------------------------------------------------------------------------- 1 | module.exports = isLowerCase = str => str === str.toLowerCase(); -------------------------------------------------------------------------------- /test/isUpperCase/isUpperCase.js: -------------------------------------------------------------------------------- 1 | module.exports = isUpperCase = str => str === str.toUpperCase(); -------------------------------------------------------------------------------- /test/sample/sample.js: -------------------------------------------------------------------------------- 1 | module.exports = sample = arr => arr[Math.floor(Math.random() * arr.length)]; -------------------------------------------------------------------------------- /test/shallowClone/shallowClone.js: -------------------------------------------------------------------------------- 1 | module.exports = shallowClone = obj => Object.assign({}, obj); -------------------------------------------------------------------------------- /test/show/show.js: -------------------------------------------------------------------------------- 1 | module.exports = show = (...el) => [...el].forEach(e => (e.style.display = '')); -------------------------------------------------------------------------------- /test/sleep/sleep.js: -------------------------------------------------------------------------------- 1 | module.exports = sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); -------------------------------------------------------------------------------- /test/sum/sum.js: -------------------------------------------------------------------------------- 1 | module.exports = sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | currentSnippet\.js 3 | *.md.temp.js 4 | .idea 5 | test.sh 6 | /*.log 7 | -------------------------------------------------------------------------------- /docs/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chinanf-boy/30-seconds-of-code/master/docs/favicon.png -------------------------------------------------------------------------------- /test/distance/distance.js: -------------------------------------------------------------------------------- 1 | module.exports = distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); -------------------------------------------------------------------------------- /test/functionName/functionName.js: -------------------------------------------------------------------------------- 1 | module.exports = functionName = fn => (console.debug(fn.name), fn); -------------------------------------------------------------------------------- /test/getStyle/getStyle.js: -------------------------------------------------------------------------------- 1 | module.exports = getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; -------------------------------------------------------------------------------- /test/hide/hide.js: -------------------------------------------------------------------------------- 1 | module.exports = hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); -------------------------------------------------------------------------------- /test/maxN/maxN.js: -------------------------------------------------------------------------------- 1 | module.exports = maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); -------------------------------------------------------------------------------- /test/minN/minN.js: -------------------------------------------------------------------------------- 1 | module.exports = minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); -------------------------------------------------------------------------------- /test/reverseString/reverseString.js: -------------------------------------------------------------------------------- 1 | module.exports = reverseString = str => [...str].reverse().join(''); -------------------------------------------------------------------------------- /test/setStyle/setStyle.js: -------------------------------------------------------------------------------- 1 | module.exports = setStyle = (el, ruleName, val) => (el.style[ruleName] = val); -------------------------------------------------------------------------------- /test/toDecimalMark/toDecimalMark.js: -------------------------------------------------------------------------------- 1 | module.exports = toDecimalMark = num => num.toLocaleString('en-US'); -------------------------------------------------------------------------------- /test/without/without.js: -------------------------------------------------------------------------------- 1 | module.exports = without = (arr, ...args) => arr.filter(v => !args.includes(v)); -------------------------------------------------------------------------------- /test/countVowels/countVowels.js: -------------------------------------------------------------------------------- 1 | module.exports = countVowels = str => (str.match(/[aeiou]/gi) || []).length; -------------------------------------------------------------------------------- /test/hasClass/hasClass.js: -------------------------------------------------------------------------------- 1 | module.exports = hasClass = (el, className) => el.classList.contains(className); -------------------------------------------------------------------------------- /test/isAbsoluteURL/isAbsoluteURL.js: -------------------------------------------------------------------------------- 1 | module.exports = isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); -------------------------------------------------------------------------------- /test/off/off.js: -------------------------------------------------------------------------------- 1 | module.exports = off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); -------------------------------------------------------------------------------- /test/cloneRegExp/cloneRegExp.js: -------------------------------------------------------------------------------- 1 | module.exports = cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); -------------------------------------------------------------------------------- /test/coalesce/coalesce.js: -------------------------------------------------------------------------------- 1 | module.exports = coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); -------------------------------------------------------------------------------- /test/coalesceFactory/coalesceFactory.js: -------------------------------------------------------------------------------- 1 | module.exports = coalesceFactory = valid => (...args) => args.find(valid); -------------------------------------------------------------------------------- /test/compose/compose.js: -------------------------------------------------------------------------------- 1 | module.exports = compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); -------------------------------------------------------------------------------- /test/everyNth/everyNth.js: -------------------------------------------------------------------------------- 1 | module.exports = everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); -------------------------------------------------------------------------------- /test/isDivisible/isDivisible.js: -------------------------------------------------------------------------------- 1 | module.exports = isDivisible = (dividend, divisor) => dividend % divisor === 0; -------------------------------------------------------------------------------- /test/isTravisCI/isTravisCI.js: -------------------------------------------------------------------------------- 1 | module.exports = isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; -------------------------------------------------------------------------------- /test/similarity/similarity.js: -------------------------------------------------------------------------------- 1 | module.exports = similarity = (arr, values) => arr.filter(v => values.includes(v)); -------------------------------------------------------------------------------- /test/takeRight/takeRight.js: -------------------------------------------------------------------------------- 1 | module.exports = takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); -------------------------------------------------------------------------------- /test/toggleClass/toggleClass.js: -------------------------------------------------------------------------------- 1 | module.exports = toggleClass = (el, className) => el.classList.toggle(className); -------------------------------------------------------------------------------- /test/words/words.js: -------------------------------------------------------------------------------- 1 | module.exports = words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); -------------------------------------------------------------------------------- /test/distinctValuesOfArray/distinctValuesOfArray.js: -------------------------------------------------------------------------------- 1 | module.exports = distinctValuesOfArray = arr => [...new Set(arr)]; -------------------------------------------------------------------------------- /test/escapeRegExp/escapeRegExp.js: -------------------------------------------------------------------------------- 1 | module.exports = escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); -------------------------------------------------------------------------------- /test/objectToPairs/objectToPairs.js: -------------------------------------------------------------------------------- 1 | module.exports = objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); -------------------------------------------------------------------------------- /test/removeVowels/removeVowels.js: -------------------------------------------------------------------------------- 1 | module.exports = removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); -------------------------------------------------------------------------------- /test/RGBToHex/RGBToHex.js: -------------------------------------------------------------------------------- 1 | module.exports = RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); -------------------------------------------------------------------------------- /test/average/average.js: -------------------------------------------------------------------------------- 1 | module.exports = average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length; -------------------------------------------------------------------------------- /test/nthElement/nthElement.js: -------------------------------------------------------------------------------- 1 | module.exports = nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; -------------------------------------------------------------------------------- /test/round/round.js: -------------------------------------------------------------------------------- 1 | module.exports = round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); -------------------------------------------------------------------------------- /test/untildify/untildify.js: -------------------------------------------------------------------------------- 1 | module.exports = untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); -------------------------------------------------------------------------------- /test/longestItem/longestItem.js: -------------------------------------------------------------------------------- 1 | module.exports = longestItem = (...vals) => [...vals].sort((a, b) => b.length - a.length)[0]; -------------------------------------------------------------------------------- /test/maxBy/maxBy.js: -------------------------------------------------------------------------------- 1 | module.exports = maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -------------------------------------------------------------------------------- /test/minBy/minBy.js: -------------------------------------------------------------------------------- 1 | module.exports = minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); -------------------------------------------------------------------------------- /test/powerset/powerset.js: -------------------------------------------------------------------------------- 1 | module.exports = powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); -------------------------------------------------------------------------------- /test/clampNumber/clampNumber.js: -------------------------------------------------------------------------------- 1 | module.exports = clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); -------------------------------------------------------------------------------- /test/isPrimitive/isPrimitive.js: -------------------------------------------------------------------------------- 1 | module.exports = isPrimitive = val => !['object', 'function'].includes(typeof val) || val === null; -------------------------------------------------------------------------------- /test/objectFromPairs/objectFromPairs.js: -------------------------------------------------------------------------------- 1 | module.exports = objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {}); -------------------------------------------------------------------------------- /test/pipeFunctions/pipeFunctions.js: -------------------------------------------------------------------------------- 1 | module.exports = pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); -------------------------------------------------------------------------------- /test/tomorrow/tomorrow.js: -------------------------------------------------------------------------------- 1 | module.exports = tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; -------------------------------------------------------------------------------- /test/validateNumber/validateNumber.js: -------------------------------------------------------------------------------- 1 | module.exports = validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; -------------------------------------------------------------------------------- /test/deepFlatten/deepFlatten.js: -------------------------------------------------------------------------------- 1 | module.exports = deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); -------------------------------------------------------------------------------- /test/filterNonUnique/filterNonUnique.js: -------------------------------------------------------------------------------- 1 | module.exports = filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); -------------------------------------------------------------------------------- /test/pick/pick.js: -------------------------------------------------------------------------------- 1 | module.exports = pick = (obj, arr) => 2 | arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); -------------------------------------------------------------------------------- /test/randomNumberInRange/randomNumberInRange.js: -------------------------------------------------------------------------------- 1 | module.exports = randomNumberInRange = (min, max) => Math.random() * (max - min) + min; -------------------------------------------------------------------------------- /test/select/select.js: -------------------------------------------------------------------------------- 1 | module.exports = select = (from, selector) => 2 | selector.split('.').reduce((prev, cur) => prev && prev[cur], from); -------------------------------------------------------------------------------- /test/transform/transform.js: -------------------------------------------------------------------------------- 1 | module.exports = transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); -------------------------------------------------------------------------------- /test/yesNo/yesNo.js: -------------------------------------------------------------------------------- 1 | module.exports = yesNo = (val, def = false) => 2 | /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; -------------------------------------------------------------------------------- /test/difference/difference.js: -------------------------------------------------------------------------------- 1 | module.exports = difference = (a, b) => { 2 | const s = new Set(b); 3 | return a.filter(x => !s.has(x)); 4 | }; -------------------------------------------------------------------------------- /test/hammingDistance/hammingDistance.js: -------------------------------------------------------------------------------- 1 | module.exports = hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; -------------------------------------------------------------------------------- /test/initializeArrayWithValues/initializeArrayWithValues.js: -------------------------------------------------------------------------------- 1 | module.exports = initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); -------------------------------------------------------------------------------- /test/mask/mask.js: -------------------------------------------------------------------------------- 1 | module.exports = mask = (cc, num = 4, mask = '*') => 2 | ('' + cc).slice(0, -num).replace(/./g, mask) + ('' + cc).slice(-num); -------------------------------------------------------------------------------- /test/capitalizeEveryWord/capitalizeEveryWord.js: -------------------------------------------------------------------------------- 1 | module.exports = capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); -------------------------------------------------------------------------------- /test/chainAsync/chainAsync.js: -------------------------------------------------------------------------------- 1 | module.exports = chainAsync = fns => { 2 | let curr = 0; 3 | const next = () => fns[curr++](next); 4 | next(); 5 | }; -------------------------------------------------------------------------------- /test/countOccurrences/countOccurrences.js: -------------------------------------------------------------------------------- 1 | module.exports = countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0); -------------------------------------------------------------------------------- /test/differenceWith/differenceWith.js: -------------------------------------------------------------------------------- 1 | module.exports = differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); -------------------------------------------------------------------------------- /test/forEachRight/forEachRight.js: -------------------------------------------------------------------------------- 1 | module.exports = forEachRight = (arr, callback) => 2 | arr 3 | .slice(0) 4 | .reverse() 5 | .forEach(callback); -------------------------------------------------------------------------------- /test/getType/getType.js: -------------------------------------------------------------------------------- 1 | module.exports = getType = v => 2 | v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); -------------------------------------------------------------------------------- /test/intersection/intersection.js: -------------------------------------------------------------------------------- 1 | module.exports = intersection = (a, b) => { 2 | const s = new Set(b); 3 | return a.filter(x => s.has(x)); 4 | }; -------------------------------------------------------------------------------- /test/runPromisesInSeries/runPromisesInSeries.js: -------------------------------------------------------------------------------- 1 | module.exports = runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); -------------------------------------------------------------------------------- /test/serializeCookie/serializeCookie.js: -------------------------------------------------------------------------------- 1 | module.exports = serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; -------------------------------------------------------------------------------- /test/truthCheckCollection/truthCheckCollection.js: -------------------------------------------------------------------------------- 1 | module.exports = truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); -------------------------------------------------------------------------------- /test/randomIntegerInRange/randomIntegerInRange.js: -------------------------------------------------------------------------------- 1 | module.exports = randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; -------------------------------------------------------------------------------- /test/redirect/redirect.js: -------------------------------------------------------------------------------- 1 | module.exports = redirect = (url, asLink = true) => 2 | asLink ? (window.location.href = url) : window.location.replace(url); -------------------------------------------------------------------------------- /test/sumBy/sumBy.js: -------------------------------------------------------------------------------- 1 | module.exports = sumBy = (arr, fn) => 2 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); -------------------------------------------------------------------------------- /test/curry/curry.js: -------------------------------------------------------------------------------- 1 | module.exports = curry = (fn, arity = fn.length, ...args) => 2 | arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); -------------------------------------------------------------------------------- /test/hasFlags/hasFlags.js: -------------------------------------------------------------------------------- 1 | module.exports = hasFlags = (...flags) => 2 | flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); -------------------------------------------------------------------------------- /test/isArrayLike/isArrayLike.js: -------------------------------------------------------------------------------- 1 | module.exports = isArrayLike = val => { 2 | try { 3 | return [...val], true; 4 | } catch (e) { 5 | return false; 6 | } 7 | }; -------------------------------------------------------------------------------- /test/sortCharactersInString/sortCharactersInString.js: -------------------------------------------------------------------------------- 1 | module.exports = sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); -------------------------------------------------------------------------------- /test/zipObject/zipObject.js: -------------------------------------------------------------------------------- 1 | module.exports = zipObject = (props, values) => 2 | props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); -------------------------------------------------------------------------------- /test/gcd/gcd.js: -------------------------------------------------------------------------------- 1 | module.exports = gcd = (...arr) => { 2 | const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); 3 | return [...arr].reduce((a, b) => _gcd(a, b)); 4 | }; -------------------------------------------------------------------------------- /test/initialize2DArray/initialize2DArray.js: -------------------------------------------------------------------------------- 1 | module.exports = initialize2DArray = (w, h, val = null) => 2 | Array(h) 3 | .fill() 4 | .map(() => Array(w).fill(val)); -------------------------------------------------------------------------------- /test/truncateString/truncateString.js: -------------------------------------------------------------------------------- 1 | module.exports = truncateString = (str, num) => 2 | str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; -------------------------------------------------------------------------------- /test/dropElements/dropElements.js: -------------------------------------------------------------------------------- 1 | module.exports = dropElements = (arr, func) => { 2 | while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); 3 | return arr; 4 | }; -------------------------------------------------------------------------------- /test/isValidJSON/isValidJSON.js: -------------------------------------------------------------------------------- 1 | module.exports = isValidJSON = obj => { 2 | try { 3 | JSON.parse(obj); 4 | return true; 5 | } catch (e) { 6 | return false; 7 | } 8 | }; -------------------------------------------------------------------------------- /test/toSafeInteger/toSafeInteger.js: -------------------------------------------------------------------------------- 1 | module.exports = toSafeInteger = num => 2 | Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); -------------------------------------------------------------------------------- /test/chunk/chunk.js: -------------------------------------------------------------------------------- 1 | module.exports = chunk = (arr, size) => 2 | Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => 3 | arr.slice(i * size, i * size + size) 4 | ); -------------------------------------------------------------------------------- /test/mapKeys/mapKeys.js: -------------------------------------------------------------------------------- 1 | module.exports = mapKeys = (obj, fn) => 2 | Object.keys(obj).reduce((acc, k) => { 3 | acc[fn(obj[k], k, obj)] = obj[k]; 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /test/mapValues/mapValues.js: -------------------------------------------------------------------------------- 1 | module.exports = mapValues = (obj, fn) => 2 | Object.keys(obj).reduce((acc, k) => { 3 | acc[k] = fn(obj[k], k, obj); 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /test/percentile/percentile.js: -------------------------------------------------------------------------------- 1 | module.exports = percentile = (arr, val) => 2 | 100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; -------------------------------------------------------------------------------- /test/getDaysDiffBetweenDates/getDaysDiffBetweenDates.js: -------------------------------------------------------------------------------- 1 | module.exports = getDaysDiffBetweenDates = (dateInitial, dateFinal) => 2 | (dateFinal - dateInitial) / (1000 * 3600 * 24); -------------------------------------------------------------------------------- /test/invertKeyValues/invertKeyValues.js: -------------------------------------------------------------------------------- 1 | module.exports = invertKeyValues = obj => 2 | Object.keys(obj).reduce((acc, key) => { 3 | acc[obj[key]] = key; 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /test/arrayToHtmlList/arrayToHtmlList.js: -------------------------------------------------------------------------------- 1 | module.exports = arrayToHtmlList = (arr, listID) => 2 | arr.map(item => (document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `)); -------------------------------------------------------------------------------- /test/averageBy/averageBy.js: -------------------------------------------------------------------------------- 1 | module.exports = averageBy = (arr, fn) => 2 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / 3 | arr.length; -------------------------------------------------------------------------------- /test/fibonacci/fibonacci.js: -------------------------------------------------------------------------------- 1 | module.exports = fibonacci = n => 2 | Array.from({ length: n }).reduce( 3 | (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), 4 | [] 5 | ); -------------------------------------------------------------------------------- /test/httpsRedirect/httpsRedirect.js: -------------------------------------------------------------------------------- 1 | module.exports = httpsRedirect = () => { 2 | if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]); 3 | }; -------------------------------------------------------------------------------- /test/timeTaken/timeTaken.js: -------------------------------------------------------------------------------- 1 | module.exports = timeTaken = callback => { 2 | console.time('timeTaken'); 3 | const r = callback(); 4 | console.timeEnd('timeTaken'); 5 | return r; 6 | }; -------------------------------------------------------------------------------- /test/capitalize/capitalize.js: -------------------------------------------------------------------------------- 1 | module.exports = capitalize = ([first, ...rest], lowerRest = false) => 2 | first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); -------------------------------------------------------------------------------- /test/createElement/createElement.js: -------------------------------------------------------------------------------- 1 | module.exports = createElement = str => { 2 | const el = document.createElement('div'); 3 | el.innerHTML = str; 4 | return el.firstElementChild; 5 | }; -------------------------------------------------------------------------------- /test/extendHex/extendHex.js: -------------------------------------------------------------------------------- 1 | module.exports = extendHex = shortHex => 2 | '#' + 3 | shortHex 4 | .slice(shortHex.startsWith('#') ? 1 : 0) 5 | .split('') 6 | .map(x => x + x) 7 | .join(''); -------------------------------------------------------------------------------- /test/indexOfAll/indexOfAll.js: -------------------------------------------------------------------------------- 1 | module.exports = indexOfAll = (arr, val) => { 2 | const indices = []; 3 | arr.forEach((el, i) => el === val && indices.push(i)); 4 | return indices; 5 | }; -------------------------------------------------------------------------------- /test/lowercaseKeys/lowercaseKeys.js: -------------------------------------------------------------------------------- 1 | module.exports = lowercaseKeys = obj => 2 | Object.keys(obj).reduce((acc, key) => { 3 | acc[key.toLowerCase()] = obj[key]; 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /test/mapObject/mapObject.js: -------------------------------------------------------------------------------- 1 | module.exports = mapObject = (arr, fn) => 2 | (a => ( 3 | (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) 4 | ))(); -------------------------------------------------------------------------------- /test/decapitalize/decapitalize.js: -------------------------------------------------------------------------------- 1 | module.exports = decapitalize = ([first, ...rest], upperRest = false) => 2 | first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); -------------------------------------------------------------------------------- /test/fibonacciCountUntilNum/fibonacciCountUntilNum.js: -------------------------------------------------------------------------------- 1 | module.exports = fibonacciCountUntilNum = num => 2 | Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); -------------------------------------------------------------------------------- /test/isPromiseLike/isPromiseLike.js: -------------------------------------------------------------------------------- 1 | module.exports = isPromiseLike = obj => 2 | obj !== null && 3 | (typeof obj === 'object' || typeof obj === 'function') && 4 | typeof obj.then === 'function'; -------------------------------------------------------------------------------- /test/once/once.js: -------------------------------------------------------------------------------- 1 | module.exports = once = fn => { 2 | let called = false; 3 | return function(...args) { 4 | if (called) return; 5 | called = true; 6 | return fn.apply(this, args); 7 | }; 8 | }; -------------------------------------------------------------------------------- /snippets/head.zh.md: -------------------------------------------------------------------------------- 1 | ### 头 2 | 3 | 返回列表的头部. 4 | 5 | 使用`ARR [0]`返回传递数组的第一个元素. 6 | 7 | ```js 8 | const head = arr => arr[0]; 9 | ``` 10 | 11 | ```js 12 | head([1, 2, 3]); // 1 13 | ``` -------------------------------------------------------------------------------- /test/README/README.js: -------------------------------------------------------------------------------- 1 | module.exports = README = e = arr => { 2 | const dt = new Date(parseInt(arr.toString().substr(6))); 3 | return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; 4 | }; -------------------------------------------------------------------------------- /test/factorial/factorial.js: -------------------------------------------------------------------------------- 1 | module.exports = factorial = n => 2 | n < 0 3 | ? (() => { 4 | throw new TypeError('Negative numbers are not allowed!'); 5 | })() 6 | : n <= 1 ? 1 : n * factorial(n - 1); -------------------------------------------------------------------------------- /test/promisify/promisify.js: -------------------------------------------------------------------------------- 1 | module.exports = promisify = func => (...args) => 2 | new Promise((resolve, reject) => 3 | func(...args, (err, result) => (err ? reject(err) : resolve(result))) 4 | ); -------------------------------------------------------------------------------- /test/sumPower/sumPower.js: -------------------------------------------------------------------------------- 1 | module.exports = sumPower = (end, power = 2, start = 1) => 2 | Array(end + 1 - start) 3 | .fill(0) 4 | .map((x, i) => (i + start) ** power) 5 | .reduce((a, b) => a + b, 0); -------------------------------------------------------------------------------- /test/isArmstrongNumber/isArmstrongNumber.js: -------------------------------------------------------------------------------- 1 | module.exports = isArmstrongNumber = digits => 2 | (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( 3 | (digits + '').split('') 4 | ); -------------------------------------------------------------------------------- /test/partition/partition.js: -------------------------------------------------------------------------------- 1 | module.exports = partition = (arr, fn) => 2 | arr.reduce( 3 | (acc, val, i, arr) => { 4 | acc[fn(val, i, arr) ? 0 : 1].push(val); 5 | return acc; 6 | }, 7 | [[], []] 8 | ); -------------------------------------------------------------------------------- /test/randomIntArrayInRange/randomIntArrayInRange.js: -------------------------------------------------------------------------------- 1 | module.exports = randomIntArrayInRange = (min, max, n = 1) => 2 | Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); -------------------------------------------------------------------------------- /test/JSONToDate/JSONToDate.js: -------------------------------------------------------------------------------- 1 | module.exports = JSONToDate = arr => { 2 | const dt = new Date(parseInt(arr.toString().substr(6))); 3 | return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; 4 | }; -------------------------------------------------------------------------------- /test/isPrime/isPrime.js: -------------------------------------------------------------------------------- 1 | module.exports = isPrime = num => { 2 | const boundary = Math.floor(Math.sqrt(num)); 3 | for (var i = 2; i <= boundary; i++) if (num % i == 0) return false; 4 | return num >= 2; 5 | }; -------------------------------------------------------------------------------- /test/lcm/lcm.js: -------------------------------------------------------------------------------- 1 | module.exports = lcm = (...arr) => { 2 | const gcd = (x, y) => (!y ? x : gcd(y, x % y)); 3 | const _lcm = (x, y) => x * y / gcd(x, y); 4 | return [...arr].reduce((a, b) => _lcm(a, b)); 5 | }; -------------------------------------------------------------------------------- /test/reducedFilter/reducedFilter.js: -------------------------------------------------------------------------------- 1 | module.exports = reducedFilter = (data, keys, fn) => 2 | data.filter(fn).map(el => 3 | keys.reduce((acc, key) => { 4 | acc[key] = el[key]; 5 | return acc; 6 | }, {}) 7 | ); -------------------------------------------------------------------------------- /test/countBy/countBy.js: -------------------------------------------------------------------------------- 1 | module.exports = countBy = (arr, fn) => 2 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { 3 | acc[val] = (acc[val] || 0) + 1; 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /test/detectDeviceType/detectDeviceType.js: -------------------------------------------------------------------------------- 1 | module.exports = detectDeviceType = () => 2 | /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) 3 | ? 'Mobile' 4 | : 'Desktop'; -------------------------------------------------------------------------------- /test/flatten/flatten.js: -------------------------------------------------------------------------------- 1 | module.exports = flatten = (arr, depth = 1) => 2 | depth != 1 3 | ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) 4 | : arr.reduce((a, v) => a.concat(v), []); -------------------------------------------------------------------------------- /test/inRange/inRange.js: -------------------------------------------------------------------------------- 1 | module.exports = inRange = (n, start, end = null) => { 2 | if (end && start > end) end = [start, (start = end)][0]; 3 | return end == null ? n >= 0 && n < start : n >= start && n < end; 4 | }; -------------------------------------------------------------------------------- /test/remove/remove.js: -------------------------------------------------------------------------------- 1 | module.exports = remove = (arr, func) => 2 | Array.isArray(arr) 3 | ? arr.filter(func).reduce((acc, val) => { 4 | arr.splice(arr.indexOf(val), 1); 5 | return acc.concat(val); 6 | }, []) 7 | : []; -------------------------------------------------------------------------------- /test/toKebabCase/toKebabCase.js: -------------------------------------------------------------------------------- 1 | module.exports = toKebabCase = str => 2 | str && 3 | str 4 | .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) 5 | .map(x => x.toLowerCase()) 6 | .join('-'); -------------------------------------------------------------------------------- /test/toSnakeCase/toSnakeCase.js: -------------------------------------------------------------------------------- 1 | module.exports = toSnakeCase = str => 2 | str && 3 | str 4 | .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) 5 | .map(x => x.toLowerCase()) 6 | .join('_'); -------------------------------------------------------------------------------- /test/bottomVisible/bottomVisible.js: -------------------------------------------------------------------------------- 1 | module.exports = bottomVisible = () => 2 | document.documentElement.clientHeight + window.scrollY >= 3 | (document.documentElement.scrollHeight || document.documentElement.clientHeight); -------------------------------------------------------------------------------- /test/getURLParameters/getURLParameters.js: -------------------------------------------------------------------------------- 1 | module.exports = getURLParameters = url => 2 | url 3 | .match(/([^?=&]+)(=([^&]*))/g) 4 | .reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {}); -------------------------------------------------------------------------------- /test/palindrome/palindrome.js: -------------------------------------------------------------------------------- 1 | module.exports = palindrome = str => { 2 | const s = str.toLowerCase().replace(/[\W_]/g, ''); 3 | return ( 4 | s === 5 | s 6 | .split('') 7 | .reverse() 8 | .join('') 9 | ); 10 | }; -------------------------------------------------------------------------------- /test/shuffle/shuffle.js: -------------------------------------------------------------------------------- 1 | module.exports = shuffle = ([...arr]) => { 2 | let m = arr.length; 3 | while (m) { 4 | const i = Math.floor(Math.random() * m--); 5 | [arr[m], arr[i]] = [arr[i], arr[m]]; 6 | } 7 | return arr; 8 | }; -------------------------------------------------------------------------------- /test/initializeArrayWithRange/initializeArrayWithRange.js: -------------------------------------------------------------------------------- 1 | module.exports = initializeArrayWithRange = (end, start = 0, step = 1) => 2 | Array.from({ length: Math.ceil((end + 1 - start) / step) }).map((v, i) => i * step + start); -------------------------------------------------------------------------------- /test/median/median.js: -------------------------------------------------------------------------------- 1 | module.exports = median = arr => { 2 | const mid = Math.floor(arr.length / 2), 3 | nums = [...arr].sort((a, b) => a - b); 4 | return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; 5 | }; -------------------------------------------------------------------------------- /test/symmetricDifference/symmetricDifference.js: -------------------------------------------------------------------------------- 1 | module.exports = symmetricDifference = (a, b) => { 2 | const sA = new Set(a), 3 | sB = new Set(b); 4 | return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; 5 | }; -------------------------------------------------------------------------------- /snippets/isNull.zh.md: -------------------------------------------------------------------------------- 1 | ### 一片空白 2 | 3 | 回报`真正`如果指定的值是`空值`,`假`除此以外. 4 | 5 | 使用严格的相等运算符来检查值和`VAL`等于`空值`. 6 | 7 | ```js 8 | const isNull = val => val === null; 9 | ``` 10 | 11 | ```js 12 | isNull(null); // true 13 | ``` -------------------------------------------------------------------------------- /snippets/last.zh.md: -------------------------------------------------------------------------------- 1 | ### 持续 2 | 3 | 返回数组中的最后一个元素. 4 | 5 | 使用`arr.length - 1`计算给定数组的最后一个元素的索引并返回它. 6 | 7 | ```js 8 | const last = arr => arr[arr.length - 1]; 9 | ``` 10 | 11 | ```js 12 | last([1, 2, 3]); // 3 13 | ``` -------------------------------------------------------------------------------- /test/groupBy/groupBy.js: -------------------------------------------------------------------------------- 1 | module.exports = groupBy = (arr, func) => 2 | arr.map(typeof func === 'function' ? func : val => val[func]).reduce((acc, val, i) => { 3 | acc[val] = (acc[val] || []).concat(arr[i]); 4 | return acc; 5 | }, {}); -------------------------------------------------------------------------------- /snippets/initial.zh.md: -------------------------------------------------------------------------------- 1 | ### 初始 2 | 3 | 返回除最后一个数组外的所有元素. 4 | 5 | 使用`arr.slice(0,-1)`返回数组的最后一个元素. 6 | 7 | ```js 8 | const initial = arr => arr.slice(0, -1); 9 | ``` 10 | 11 | ```js 12 | initial([1, 2, 3]); // [1,2] 13 | ``` -------------------------------------------------------------------------------- /snippets/isArray.zh.md: -------------------------------------------------------------------------------- 1 | ### IsArray的 2 | 3 | 检查给定的参数是否是一个数组. 4 | 5 | 使用`array.isarray()`检查一个值是否被分类为一个数组. 6 | 7 | ```js 8 | const isArray = val => Array.isArray(val); 9 | ``` 10 | 11 | ```js 12 | isArray([1]); // true 13 | ``` -------------------------------------------------------------------------------- /snippets/isString.zh.md: -------------------------------------------------------------------------------- 1 | ### isstring 2 | 3 | 检查给定的参数是否是一个字符串. 4 | 5 | 使用`类型`检查一个值是否被分类为一个字符串原语. 6 | 7 | ```js 8 | const isString = val => typeof val === 'string'; 9 | ``` 10 | 11 | ```js 12 | isString('10'); // true 13 | ``` -------------------------------------------------------------------------------- /test/size/size.js: -------------------------------------------------------------------------------- 1 | module.exports = size = val => 2 | Array.isArray(val) 3 | ? val.length 4 | : val && typeof val === 'object' 5 | ? val.size || val.length || Object.keys(val).length 6 | : typeof val === 'string' ? new Blob([val]).size : 0; -------------------------------------------------------------------------------- /snippets/isSymbol.zh.md: -------------------------------------------------------------------------------- 1 | ### issymbol 2 | 3 | 检查给定的参数是否是一个符号. 4 | 5 | 使用`类型`检查一个值是否被分类为符号原语. 6 | 7 | ```js 8 | const isSymbol = val => typeof val === 'symbol'; 9 | ``` 10 | 11 | ```js 12 | isSymbol(Symbol('x')); // true 13 | ``` -------------------------------------------------------------------------------- /test/escapeHTML/escapeHTML.js: -------------------------------------------------------------------------------- 1 | module.exports = escapeHTML = str => 2 | str.replace( 3 | /[&<>'"]/g, 4 | tag => 5 | ({ 6 | '&': '&', 7 | '<': '<', 8 | '>': '>', 9 | "'": ''', 10 | '"': '"' 11 | }[tag] || tag) 12 | ); -------------------------------------------------------------------------------- /test/join/join.js: -------------------------------------------------------------------------------- 1 | module.exports = join = (arr, separator = ',', end = separator) => 2 | arr.reduce( 3 | (acc, val, i) => 4 | i == arr.length - 2 5 | ? acc + val + end 6 | : i == arr.length - 1 ? acc + val : acc + val + separator, 7 | '' 8 | ); -------------------------------------------------------------------------------- /test/randomHexColorCode/randomHexColorCode.js: -------------------------------------------------------------------------------- 1 | module.exports = randomHexColorCode = () => { 2 | let n = ((Math.random() * 0xfffff) | 0).toString(16); 3 | return '#' + (n.length !== 6 ? ((Math.random() * 0xf) | 0).toString(16) + n : n); 4 | }; -------------------------------------------------------------------------------- /test/sdbm/sdbm.js: -------------------------------------------------------------------------------- 1 | module.exports = sdbm = str => { 2 | let arr = str.split(''); 3 | return arr.reduce( 4 | (hashCode, currentVal) => 5 | (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), 6 | 0 7 | ); 8 | }; -------------------------------------------------------------------------------- /test/speechSynthesis/speechSynthesis.js: -------------------------------------------------------------------------------- 1 | module.exports = speechSynthesis = message => { 2 | const msg = new SpeechSynthesisUtterance(message); 3 | msg.voice = window.speechSynthesis.getVoices()[0]; 4 | window.speechSynthesis.speak(msg); 5 | }; -------------------------------------------------------------------------------- /test/fromCamelCase/fromCamelCase.js: -------------------------------------------------------------------------------- 1 | module.exports = fromCamelCase = (str, separator = '_') => 2 | str 3 | .replace(/([a-z\d])([A-Z])/g, '$1' + separator + '$2') 4 | .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + separator + '$2') 5 | .toLowerCase(); -------------------------------------------------------------------------------- /test/functions/functions.js: -------------------------------------------------------------------------------- 1 | module.exports = functions = (obj, inherited = false) => 2 | (inherited 3 | ? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))] 4 | : Object.keys(obj) 5 | ).filter(key => typeof obj[key] === 'function'); -------------------------------------------------------------------------------- /test/geometricProgression/geometricProgression.js: -------------------------------------------------------------------------------- 1 | module.exports = geometricProgression = (end, start = 1, step = 2) => 2 | Array.from({ length: Math.floor(Math.log(end / start) / Math.log(step)) + 1 }).map( 3 | (v, i) => start * step ** i 4 | ); -------------------------------------------------------------------------------- /test/getScrollPosition/getScrollPosition.js: -------------------------------------------------------------------------------- 1 | module.exports = getScrollPosition = (el = window) => ({ 2 | x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 3 | y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 4 | }); -------------------------------------------------------------------------------- /test/pull/pull.js: -------------------------------------------------------------------------------- 1 | module.exports = pull = (arr, ...args) => { 2 | let argState = Array.isArray(args[0]) ? args[0] : args; 3 | let pulled = arr.filter((v, i) => !argState.includes(v)); 4 | arr.length = 0; 5 | pulled.forEach(v => arr.push(v)); 6 | }; -------------------------------------------------------------------------------- /snippets/currentURL.zh.md: -------------------------------------------------------------------------------- 1 | ### CURRENTURL 2 | 3 | 返回当前的网址. 4 | 5 | 使用`window.location.href`获取当前网址. 6 | 7 | ```js 8 | const currentURL = () => window.location.href; 9 | ``` 10 | 11 | ```js 12 | currentURL(); // 'https://google.com' 13 | ``` -------------------------------------------------------------------------------- /snippets_archive/collatz.zh.md: -------------------------------------------------------------------------------- 1 | ### 在Collat​​z 2 | 3 | 应用collat​​z算法. 4 | 5 | 如果`ñ`甚至是回报`n / 2个`. `否则,返回`3N + 1. 6 | 7 | ```js 8 | const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); 9 | ``` 10 | 11 | ```js 12 | collatz(8); // 4 13 | ``` -------------------------------------------------------------------------------- /test/UUIDGeneratorBrowser/UUIDGeneratorBrowser.js: -------------------------------------------------------------------------------- 1 | module.exports = UUIDGeneratorBrowser = () => 2 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 3 | (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) 4 | ); -------------------------------------------------------------------------------- /test/parseCookie/parseCookie.js: -------------------------------------------------------------------------------- 1 | module.exports = parseCookie = str => 2 | str 3 | .split(';') 4 | .map(v => v.split('=')) 5 | .reduce((acc, v) => { 6 | acc[decodeURIComponent(v[0].trim())] = decodeURIComponent(v[1].trim()); 7 | return acc; 8 | }, {}); -------------------------------------------------------------------------------- /test/sampleSize/sampleSize.js: -------------------------------------------------------------------------------- 1 | module.exports = sampleSize = ([...arr], n = 1) => { 2 | let m = arr.length; 3 | while (m) { 4 | const i = Math.floor(Math.random() * m--); 5 | [arr[m], arr[i]] = [arr[i], arr[m]]; 6 | } 7 | return arr.slice(0, n); 8 | }; -------------------------------------------------------------------------------- /snippet-template.zh.md: -------------------------------------------------------------------------------- 1 | ### functionname 2 | 3 | 简要地解释片段的作用. 4 | 5 | 简要地解释片段是如何工作的. 6 | 7 | ```js 8 | const functionName = arguments => 9 | {functionBody} 10 | ``` 11 | 12 | ```js 13 | functionName('sampleInput') // 'sampleOutput' 14 | ``` -------------------------------------------------------------------------------- /snippets/head.md: -------------------------------------------------------------------------------- 1 | ### head 2 | 3 | Returns the head of a list. 4 | 5 | Use `arr[0]` to return the first element of the passed array. 6 | 7 | ```js 8 | const head = arr => arr[0]; 9 | ``` 10 | 11 | ```js 12 | head([1, 2, 3]); // 1 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/isEven.zh.md: -------------------------------------------------------------------------------- 1 | ### 甚至 2 | 3 | 回报`真正`如果给定的数字是偶数,`假`除此以外. 4 | 5 | 检查一个数是奇数还是使用模(`%`)operator.returns`真正`如果数量是偶数,`假`如果数字是奇数. 6 | 7 | ```js 8 | const isEven = num => num % 2 === 0; 9 | ``` 10 | 11 | ```js 12 | isEven(3); // false 13 | ``` -------------------------------------------------------------------------------- /test/merge/merge.js: -------------------------------------------------------------------------------- 1 | module.exports = merge = (...objs) => 2 | [...objs].reduce( 3 | (acc, obj) => 4 | Object.keys(obj).reduce((a, k) => { 5 | acc[k] = acc.hasOwnProperty(k) ? [].concat(acc[k]).concat(obj[k]) : obj[k]; 6 | return acc; 7 | }, {}), 8 | {} 9 | ); -------------------------------------------------------------------------------- /test/quickSort/quickSort.js: -------------------------------------------------------------------------------- 1 | module.exports = quickSort = ([n, ...nums], desc) => 2 | isNaN(n) 3 | ? [] 4 | : [ 5 | ...quickSort(nums.filter(v => (desc ? v > n : v <= n)), desc), 6 | n, 7 | ...quickSort(nums.filter(v => (!desc ? v > n : v <= n)), desc) 8 | ]; -------------------------------------------------------------------------------- /test/scrollToTop/scrollToTop.js: -------------------------------------------------------------------------------- 1 | module.exports = scrollToTop = () => { 2 | const c = document.documentElement.scrollTop || document.body.scrollTop; 3 | if (c > 0) { 4 | window.requestAnimationFrame(scrollToTop); 5 | window.scrollTo(0, c - c / 8); 6 | } 7 | }; -------------------------------------------------------------------------------- /test/sortedIndex/sortedIndex.js: -------------------------------------------------------------------------------- 1 | module.exports = sortedIndex = (arr, n) => { 2 | const isDescending = arr[0] > arr[arr.length - 1]; 3 | const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); 4 | return index === -1 ? arr.length : index; 5 | }; -------------------------------------------------------------------------------- /snippets/isNumber.zh.md: -------------------------------------------------------------------------------- 1 | ### ISNUMBER 2 | 3 | 检查给定的参数是否是一个数字. 4 | 5 | 使用`类型`检查一个值是否被分类为数字原语. 6 | 7 | ```js 8 | const isNumber = val => typeof val === 'number'; 9 | ``` 10 | 11 | ```js 12 | isNumber('1'); // false 13 | isNumber(1); // true 14 | ``` -------------------------------------------------------------------------------- /snippets/union.zh.md: -------------------------------------------------------------------------------- 1 | ### 联盟 2 | 3 | 返回两个数组中的任何一个元素. 4 | 5 | 创建一个`组`与所有值`一个`和`b`并转换成一个数组. 6 | 7 | ```js 8 | const union = (a, b) => Array.from(new Set([...a, ...b])); 9 | ``` 10 | 11 | ```js 12 | union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] 13 | ``` -------------------------------------------------------------------------------- /test/isSorted/isSorted.js: -------------------------------------------------------------------------------- 1 | module.exports = isSorted = arr => { 2 | const direction = arr[0] > arr[1] ? -1 : 1; 3 | for (let [i, val] of arr.entries()) 4 | if (i === arr.length - 1) return direction; 5 | else if ((val - arr[i + 1]) * direction > 0) return 0; 6 | }; -------------------------------------------------------------------------------- /snippets/distance.zh.md: -------------------------------------------------------------------------------- 1 | ### 距离 2 | 3 | 返回两点之间的距离. 4 | 5 | 使用`math.hypot()`计算两点之间的欧氏距离. 6 | 7 | ```js 8 | const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); 9 | ``` 10 | 11 | ```js 12 | distance(1, 1, 2, 3); // 2.23606797749979 13 | ``` -------------------------------------------------------------------------------- /snippets/negate.zh.md: -------------------------------------------------------------------------------- 1 | ### 否定 2 | 3 | 否定谓词功能. 4 | 5 | 采用谓词函数并应用非运算符(`!`)与它的论据. 6 | 7 | ```js 8 | const negate = func => (...args) => !func(...args); 9 | ``` 10 | 11 | ```js 12 | [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 == 0)); // [ 1, 3, 5 ] 13 | ``` -------------------------------------------------------------------------------- /snippets/sum.zh.md: -------------------------------------------------------------------------------- 1 | ### 和 2 | 3 | 返回两个或更多数字/数组的总和. 4 | 5 | 使用`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`. 6 | 7 | ```js 8 | const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); 9 | ``` 10 | 11 | ```js 12 | sum(...[1, 2, 3, 4]); // 10 13 | ``` -------------------------------------------------------------------------------- /test/zip/zip.js: -------------------------------------------------------------------------------- 1 | module.exports = zip = (...arrays) => { 2 | const maxLength = Math.max(...arrays.map(x => x.length)); 3 | return Array.from({ length: maxLength }).map((_, i) => { 4 | return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]); 5 | }); 6 | }; -------------------------------------------------------------------------------- /snippets/isDivisible.zh.md: -------------------------------------------------------------------------------- 1 | ### isdivisible 2 | 3 | 检查第一个数字参数是否可被第二个数字整除. 4 | 5 | 使用模运算符(`%`)来检查余数是否相等`0`. 6 | 7 | ```js 8 | const isDivisible = (dividend, divisor) => dividend % divisor === 0; 9 | ``` 10 | 11 | ```js 12 | isDivisible(6, 3); // true 13 | ``` -------------------------------------------------------------------------------- /test/unescapeHTML/unescapeHTML.js: -------------------------------------------------------------------------------- 1 | module.exports = unescapeHTML = str => 2 | str.replace( 3 | /&|<|>|'|"/g, 4 | tag => 5 | ({ 6 | '&': '&', 7 | '<': '<', 8 | '>': '>', 9 | ''': "'", 10 | '"': '"' 11 | }[tag] || tag) 12 | ); -------------------------------------------------------------------------------- /snippets/isBoolean.zh.md: -------------------------------------------------------------------------------- 1 | ### isboolean 2 | 3 | 检查给定的参数是否是一个本地布尔元素. 4 | 5 | 使用`类型`检查一个值是否被分类为一个布尔原语. 6 | 7 | ```js 8 | const isBoolean = val => typeof val === 'boolean'; 9 | ``` 10 | 11 | ```js 12 | isBoolean(null); // false 13 | isBoolean(false); // true 14 | ``` -------------------------------------------------------------------------------- /snippets/take.zh.md: -------------------------------------------------------------------------------- 1 | ### 采取 2 | 3 | 返回一个包含n个元素的数组. 4 | 5 | 使用`array.slice()`用数组创建一个分片`ñ`从头开始的元素. 6 | 7 | ```js 8 | const take = (arr, n = 1) => arr.slice(0, n); 9 | ``` 10 | 11 | ```js 12 | take([1, 2, 3], 5); // [1, 2, 3] 13 | take([1, 2, 3], 0); // [] 14 | ``` -------------------------------------------------------------------------------- /snippets/isFunction.zh.md: -------------------------------------------------------------------------------- 1 | ### isfunction 2 | 3 | 检查给定的参数是否是一个函数. 4 | 5 | 使用`类型`检查一个值是否被分类为一个函数原语. 6 | 7 | ```js 8 | const isFunction = val => typeof val === 'function'; 9 | ``` 10 | 11 | ```js 12 | isFunction('x'); // false 13 | isFunction(x => x); // true 14 | ``` -------------------------------------------------------------------------------- /snippets/tail.zh.md: -------------------------------------------------------------------------------- 1 | ### 尾巴 2 | 3 | 返回数组中除第一个元素之外的所有元素. 4 | 5 | 返回`array.slice(1)`如果数组的`长度`超过`1`否则,返回整个数组. 6 | 7 | ```js 8 | const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); 9 | ``` 10 | 11 | ```js 12 | tail([1, 2, 3]); // [2,3] 13 | tail([1]); // [1] 14 | ``` -------------------------------------------------------------------------------- /test/memoize/memoize.js: -------------------------------------------------------------------------------- 1 | module.exports = memoize = fn => { 2 | const cache = new Map(); 3 | const cached = function(val) { 4 | return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val); 5 | }; 6 | cached.cache = cache; 7 | return cached; 8 | }; -------------------------------------------------------------------------------- /test/on/on.js: -------------------------------------------------------------------------------- 1 | module.exports = on = (el, evt, fn, opts = {}) => { 2 | const delegatorFn = e => e.target.matches(opts.target) && fn.call(e.target, e); 3 | el.addEventListener(evt, opts.target ? delegatorFn : fn, opts.options || false); 4 | if (opts.target) return delegatorFn; 5 | }; -------------------------------------------------------------------------------- /dist/NOTICE.zh.md: -------------------------------------------------------------------------------- 1 | # 警告! 2 | 3 | 该`_30s`模块没有生产准备好. 4 | 5 | 不要在生产网站上使用它,这是严格的测试目的. 6 | 7 | 片段没有任何单元测试写入,将不可靠. `片段名称可以并且将在未经通知的情况下在小版本之间改变. `给出的版本 8 | 9 | - `0.x.y`: 10 | - `X`表示片段名称更改. 11 | 12 | ÿ`表示一个新的片段或修复. `如果你的项目不严肃,你不关心上述问题,你会想要使用`ES5`版本,也包括巴别塔,填充工具获得最广泛的浏览器支持. -------------------------------------------------------------------------------- /snippets/currentURL.md: -------------------------------------------------------------------------------- 1 | ### currentURL 2 | 3 | Returns the current URL. 4 | 5 | Use `window.location.href` to get current URL. 6 | 7 | ```js 8 | const currentURL = () => window.location.href; 9 | ``` 10 | 11 | ```js 12 | currentURL(); // 'https://google.com' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/escapeRegExp.zh.md: -------------------------------------------------------------------------------- 1 | ### escaperegexp 2 | 3 | 转义字符串以在正则表达式中使用. 4 | 5 | 使用`与string.replace()`逃避特殊字符. 6 | 7 | ```js 8 | const escapeRegExp = str => str.replace(/[.*+?^${}()Ɯ[\]\\]/g, '\\$&'); 9 | ``` 10 | 11 | ```js 12 | escapeRegExp('(test)'); // \\(test\\) 13 | ``` -------------------------------------------------------------------------------- /snippets_archive/collatz.md: -------------------------------------------------------------------------------- 1 | ### collatz 2 | 3 | Applies the Collatz algorithm. 4 | 5 | If `n` is even, return `n/2`. Otherwise, return `3n+1`. 6 | 7 | ```js 8 | const collatz = n => (n % 2 == 0 ? n / 2 : 3 * n + 1); 9 | ``` 10 | 11 | ```js 12 | collatz(8); // 4 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/digitize.zh.md: -------------------------------------------------------------------------------- 1 | ### 数字化 2 | 3 | 将数字转换为数字数组. 4 | 5 | 将数字转换为字符串,使用扩展运算符(`...`)来构建一个array.use`array.map()`和`parseInt函数()`将每个值转换为一个整数. 6 | 7 | ```js 8 | const digitize = n => [...`${n}`].map(i => parseInt(i)); 9 | ``` 10 | 11 | ```js 12 | digitize(123); // [1, 2, 3] 13 | ``` -------------------------------------------------------------------------------- /snippets/coalesce.zh.md: -------------------------------------------------------------------------------- 1 | ### 合并 2 | 3 | 返回第一个非空/未定义的参数. 4 | 5 | 使用`array.find()`返回第一个非`空值`/`未定义`论据. 6 | 7 | ```js 8 | const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); 9 | ``` 10 | 11 | ```js 12 | coalesce(null, undefined, '', NaN, 'Waldo'); // "" 13 | ``` -------------------------------------------------------------------------------- /snippets/isArray.md: -------------------------------------------------------------------------------- 1 | ### isArray 2 | 3 | Checks if the given argument is an array. 4 | 5 | Use `Array.isArray()` to check if a value is classified as an array. 6 | 7 | ```js 8 | const isArray = val => Array.isArray(val); 9 | ``` 10 | 11 | ```js 12 | isArray([1]); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /test/httpDelete/httpDelete.js: -------------------------------------------------------------------------------- 1 | module.exports = httpDelete = (url, callback, err = console.error) => { 2 | const request = new XMLHttpRequest(); 3 | request.open("DELETE", url, true); 4 | request.onload = () => callback(request); 5 | request.onerror = () => err(request); 6 | request.send(); 7 | }; -------------------------------------------------------------------------------- /test/httpGet/httpGet.js: -------------------------------------------------------------------------------- 1 | module.exports = httpGet = (url, callback, err = console.error) => { 2 | const request = new XMLHttpRequest(); 3 | request.open('GET', url, true); 4 | request.onload = () => callback(request.responseText); 5 | request.onerror = () => err(request); 6 | request.send(); 7 | }; -------------------------------------------------------------------------------- /snippets/everyNth.zh.md: -------------------------------------------------------------------------------- 1 | ### everynth 2 | 3 | 返回数组中的每个第n个元素. 4 | 5 | 使用`array.filter()`创建一个包含给定数组的每个第n个元素的新数组. 6 | 7 | ```js 8 | const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); 9 | ``` 10 | 11 | ```js 12 | everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] 13 | ``` -------------------------------------------------------------------------------- /snippets/sample.zh.md: -------------------------------------------------------------------------------- 1 | ### 样品 2 | 3 | 从数组中返回一个随机元素. 4 | 5 | 使用`的Math.random()`生成一个随机数,乘以`长度`并使用它将其四舍五入到最接近的整数`math.floor()`这个方法也适用于字符串. 6 | 7 | ```js 8 | const sample = arr => arr[Math.floor(Math.random() * arr.length)]; 9 | ``` 10 | 11 | ```js 12 | sample([3, 7, 9, 11]); // 9 13 | ``` -------------------------------------------------------------------------------- /snippet-template.md: -------------------------------------------------------------------------------- 1 | ### functionName 2 | 3 | Explain briefly what the snippet does. 4 | 5 | Explain briefly how the snippet works. 6 | 7 | ```js 8 | const functionName = arguments => 9 | {functionBody} 10 | ``` 11 | 12 | ```js 13 | functionName('sampleInput') // 'sampleOutput' 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/distinctValuesOfArray.zh.md: -------------------------------------------------------------------------------- 1 | ### distinctvaluesofarray 2 | 3 | 返回数组的所有不同值. 4 | 5 | 使用es6`组`和`...休息`操作员放弃所有重复的值. 6 | 7 | ```js 8 | const distinctValuesOfArray = arr => [...new Set(arr)]; 9 | ``` 10 | 11 | ```js 12 | distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5] 13 | ``` -------------------------------------------------------------------------------- /snippets/isString.md: -------------------------------------------------------------------------------- 1 | ### isString 2 | 3 | Checks if the given argument is a string. 4 | 5 | Use `typeof` to check if a value is classified as a string primitive. 6 | 7 | ```js 8 | const isString = val => typeof val === 'string'; 9 | ``` 10 | 11 | ```js 12 | isString('10'); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/round.zh.md: -------------------------------------------------------------------------------- 1 | ### 回合 2 | 3 | 将数字四舍五入到指定的数字位数. 4 | 5 | 使用`math.round()`和模板文字将数字四舍五入为指定的位数. 第二个参数,`小数点`舍入为一个整数. 6 | 7 | ```js 8 | const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); 9 | ``` 10 | 11 | ```js 12 | round(1.005, 2); // 1.01 13 | ``` -------------------------------------------------------------------------------- /snippets/similarity.zh.md: -------------------------------------------------------------------------------- 1 | ### 相似 2 | 3 | 返回出现在两个数组中的元素数组. 4 | 5 | 使用`array.filter()`删除不属于的值`值`,确定使用`array.includes()`. 6 | 7 | ```js 8 | const similarity = (arr, values) => arr.filter(v => values.includes(v)); 9 | ``` 10 | 11 | ```js 12 | similarity([1, 2, 3], [1, 2, 4]); // [1,2] 13 | ``` -------------------------------------------------------------------------------- /test/howManyTimes/howManyTimes.js: -------------------------------------------------------------------------------- 1 | module.exports = howManyTimes = (num, divisor) => { 2 | if (divisor === 1 || divisor === -1) return Infinity; 3 | if (divisor === 0) return 0; 4 | let i = 0; 5 | while (Number.isInteger(num / divisor)) { 6 | i++; 7 | num = num / divisor; 8 | } 9 | return i; 10 | }; -------------------------------------------------------------------------------- /snippets/findLast.zh.md: -------------------------------------------------------------------------------- 1 | ### FindLast中 2 | 3 | 返回提供的函数返回真值的最后一个元素. 4 | 5 | 使用`array.filter()`去除其中的元素`FN`返回falsey值,`array.slice(-1)`得到最后一个. 6 | 7 | ```js 8 | const findLast = (arr, fn) => arr.filter(fn).slice(-1); 9 | ``` 10 | 11 | ```js 12 | findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 13 | ``` -------------------------------------------------------------------------------- /snippets/getStyle.zh.md: -------------------------------------------------------------------------------- 1 | ### GetStyle为 2 | 3 | 返回指定元素的css规则的值. 4 | 5 | 使用`window.getcomputedstyle()`获取指定元素的css规则的值. 6 | 7 | ```js 8 | const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; 9 | ``` 10 | 11 | ```js 12 | getStyle(document.querySelector('p'), 'font-size'); // '16px' 13 | ``` -------------------------------------------------------------------------------- /snippets/shallowClone.zh.md: -------------------------------------------------------------------------------- 1 | ### shallowclone 2 | 3 | 创建一个对象的浅层克隆. 4 | 5 | 使用`object.assign()`和一个空的对象(`{}`)创建原始的浅层克隆. 6 | 7 | ```js 8 | const shallowClone = obj => Object.assign({}, obj); 9 | ``` 10 | 11 | ```js 12 | const a = { x: true, y: 1 }; 13 | const b = shallowClone(a); // a !== b 14 | ``` -------------------------------------------------------------------------------- /snippets/spreadOver.zh.md: -------------------------------------------------------------------------------- 1 | ### 传播开来 2 | 3 | 接受一个可变参数函数并返回一个闭包,该闭包接受一个参数数组映射到函数的输入. 4 | 5 | 使用闭包和传播运算符(`...`)将参数数组映射到函数的输入. 6 | 7 | ```js 8 | const spreadOver = fn => argsArr => fn(...argsArr); 9 | ``` 10 | 11 | ```js 12 | const arrayMax = spreadOver(Math.max); 13 | arrayMax([1, 2, 3]); // 3 14 | ``` -------------------------------------------------------------------------------- /snippets/filterNonUnique.zh.md: -------------------------------------------------------------------------------- 1 | ### filternonunique 2 | 3 | 过滤掉数组中的非唯一值. 4 | 5 | 使用`array.filter()`只包含唯一值的数组 6 | 7 | ```js 8 | const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); 9 | ``` 10 | 11 | ```js 12 | filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] 13 | ``` -------------------------------------------------------------------------------- /snippets/isSymbol.md: -------------------------------------------------------------------------------- 1 | ### isSymbol 2 | 3 | Checks if the given argument is a symbol. 4 | 5 | Use `typeof` to check if a value is classified as a symbol primitive. 6 | 7 | ```js 8 | const isSymbol = val => typeof val === 'symbol'; 9 | ``` 10 | 11 | ```js 12 | isSymbol(Symbol('x')); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/last.md: -------------------------------------------------------------------------------- 1 | ### last 2 | 3 | Returns the last element in an array. 4 | 5 | Use `arr.length - 1` to compute the index of the last element of the given array and returning it. 6 | 7 | ```js 8 | const last = arr => arr[arr.length - 1]; 9 | ``` 10 | 11 | ```js 12 | last([1, 2, 3]); // 3 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/objectFromPairs.zh.md: -------------------------------------------------------------------------------- 1 | ### objectfrompairs 2 | 3 | 从给定的键值对创建一个对象. 4 | 5 | 使用`array.reduce()`创建和组合键值对. 6 | 7 | ```js 8 | const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {}); 9 | ``` 10 | 11 | ```js 12 | objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2} 13 | ``` -------------------------------------------------------------------------------- /snippets_archive/countVowels.zh.md: -------------------------------------------------------------------------------- 1 | ### countvowels 2 | 3 | retuns`数`提供的字符串中的元音. 4 | 5 | 使用正则表达式来计算元音的数量`(a,e,i,o,u)`在一个`串`. 6 | 7 | ```js 8 | const countVowels = str => (str.match(/[aeiou]/gi) ƜƜ []).length; 9 | ``` 10 | 11 | ```js 12 | countVowels('foobar'); // 3 13 | countVowels('gym'); // 0 14 | ``` -------------------------------------------------------------------------------- /test/pullAtIndex/pullAtIndex.js: -------------------------------------------------------------------------------- 1 | module.exports = pullAtIndex = (arr, pullArr) => { 2 | let removed = []; 3 | let pulled = arr 4 | .map((v, i) => (pullArr.includes(i) ? removed.push(v) : v)) 5 | .filter((v, i) => !pullArr.includes(i)); 6 | arr.length = 0; 7 | pulled.forEach(v => arr.push(v)); 8 | return removed; 9 | }; -------------------------------------------------------------------------------- /snippets/compact.zh.md: -------------------------------------------------------------------------------- 1 | ### 紧凑 2 | 3 | 从数组中删除falsey值. 4 | 5 | 使用`array.filter()`过滤出错误的值(`假`,`空值`,`0`,`""`,`未定义`,和`楠`). 6 | 7 | ```js 8 | const compact = arr => arr.filter(Boolean); 9 | ``` 10 | 11 | ```js 12 | compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] 13 | ``` -------------------------------------------------------------------------------- /snippets/functionName.zh.md: -------------------------------------------------------------------------------- 1 | ### functionname 2 | 3 | 记录一个函数的名字. 4 | 5 | 使用`console.debug()`和`名称`传入的方法的属性将方法的名称记录到`调试`控制台的通道. 6 | 7 | ```js 8 | const functionName = fn => (console.debug(fn.name), fn); 9 | ``` 10 | 11 | ```js 12 | functionName(Math.max); // max (logged in debug channel of console) 13 | ``` -------------------------------------------------------------------------------- /snippets/initial.md: -------------------------------------------------------------------------------- 1 | ### initial 2 | 3 | Returns all the elements of an array except the last one. 4 | 5 | Use `arr.slice(0,-1)` to return all but the last element of the array. 6 | 7 | ```js 8 | const initial = arr => arr.slice(0, -1); 9 | ``` 10 | 11 | ```js 12 | initial([1, 2, 3]); // [1,2] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/powerset.zh.md: -------------------------------------------------------------------------------- 1 | ### 幂 2 | 3 | 返回给定数组数组的powerset. 4 | 5 | 使用`array.reduce()`结合`array.map()`遍历元素并组合成一个包含所有组合的数组. 6 | 7 | ```js 8 | const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); 9 | ``` 10 | 11 | ```js 12 | powerset([1, 2]); // [[], [1], [2], [2,1]] 13 | ``` -------------------------------------------------------------------------------- /snippets/reverseString.zh.md: -------------------------------------------------------------------------------- 1 | ### reversestring 2 | 3 | 反转一个字符串. 4 | 5 | 使用扩展运算符(`...`)和`array.reverse()`以反转string.combine字符中的字符顺序来获取一个字符串`的string.join( '')`. 6 | 7 | ```js 8 | const reverseString = str => [...str].reverse().join(''); 9 | ``` 10 | 11 | ```js 12 | reverseString('foobar'); // 'raboof' 13 | ``` -------------------------------------------------------------------------------- /test/fibonacciUntilNum/fibonacciUntilNum.js: -------------------------------------------------------------------------------- 1 | module.exports = fibonacciUntilNum = num => { 2 | let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); 3 | return Array.from({ length: n }).reduce( 4 | (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), 5 | [] 6 | ); 7 | }; -------------------------------------------------------------------------------- /snippets/byteSize.zh.md: -------------------------------------------------------------------------------- 1 | ### bytesize 2 | 3 | 以字节为单位返回字符串的长度. 4 | 5 | 将给定的字符串转换为[`BLOB`目的](https://developer.mozilla.org/en-US/docs/Web/API/Blob)并找到它`尺寸`. 6 | 7 | ```js 8 | const byteSize = str => new Blob([str]).size; 9 | ``` 10 | 11 | ```js 12 | byteSize('😀'); // 4 13 | byteSize('Hello World'); // 11 14 | ``` -------------------------------------------------------------------------------- /snippets/objectToPairs.zh.md: -------------------------------------------------------------------------------- 1 | ### objecttopairs 2 | 3 | 从一个对象中创建一个键 - 值对数组的数组. 4 | 5 | 使用`object.keys()`和`array.map()`遍历对象的键并生成一个包含键值对的数组. 6 | 7 | ```js 8 | const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); 9 | ``` 10 | 11 | ```js 12 | objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]] 13 | ``` -------------------------------------------------------------------------------- /snippets/randomNumberInRange.zh.md: -------------------------------------------------------------------------------- 1 | ### randomnumberinrange 2 | 3 | 返回指定范围内的一个随机数. 4 | 5 | 使用`的Math.random()`生成一个随机值,使用乘法将其映射到所需的范围. 6 | 7 | ```js 8 | const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; 9 | ``` 10 | 11 | ```js 12 | randomNumberInRange(2, 10); // 6.0211363285087005 13 | ``` -------------------------------------------------------------------------------- /snippets/show.zh.md: -------------------------------------------------------------------------------- 1 | ### 显示 2 | 3 | 显示了所有指定的元素. 4 | 5 | 使用扩展运算符(`...`)和`array.foreach()`清除`显示`属性指定的每个元素. 6 | 7 | ```js 8 | const show = (...el) => [...el].forEach(e => (e.style.display = '')); 9 | ``` 10 | 11 | ```js 12 | show(...document.querySelectorAll('img')); // Shows all elements on the page 13 | ``` -------------------------------------------------------------------------------- /snippets/splitLines.zh.md: -------------------------------------------------------------------------------- 1 | ### splitlines 2 | 3 | 将多行字符串拆分成一行数组. 4 | 5 | 使用`string.split()`和一个正则表达式来匹配换行符并创建一个数组. 6 | 7 | ```js 8 | const splitLines = str => str.split(/\r?\n/); 9 | ``` 10 | 11 | ```js 12 | splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , ''] 13 | ``` -------------------------------------------------------------------------------- /snippets/takeRight.zh.md: -------------------------------------------------------------------------------- 1 | ### takeright 2 | 3 | 返回一个包含n个元素的数组. 4 | 5 | 使用`array.slice()`用来创建一个数组的切片`ñ`从最后采取的元素. 6 | 7 | ```js 8 | const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); 9 | ``` 10 | 11 | ```js 12 | takeRight([1, 2, 3], 2); // [ 2, 3 ] 13 | takeRight([1, 2, 3]); // [3] 14 | ``` -------------------------------------------------------------------------------- /snippets/untildify.zh.md: -------------------------------------------------------------------------------- 1 | ### untildify 2 | 3 | 将波浪号路径转换为绝对路径. 4 | 5 | 使用`与string.replace()`用正则表达式和`os.homedir()`取代`〜`在主目录的路径的开始. 6 | 7 | ```js 8 | const untildify = str => str.replace(/^~($Ɯ\/Ɯ\\)/, `${require('os').homedir()}$1`); 9 | ``` 10 | 11 | ```js 12 | untildify('~/node'); // '/Users/aUser/node' 13 | ``` -------------------------------------------------------------------------------- /test/toCamelCase/toCamelCase.js: -------------------------------------------------------------------------------- 1 | module.exports = toCamelCase = str => { 2 | let s = 3 | str && 4 | str 5 | .match(/[A-Z]{2,}(?=[A-Z][a-z]+[0-9]*|\b)|[A-Z]?[a-z]+[0-9]*|[A-Z]|[0-9]+/g) 6 | .map(x => x.slice(0, 1).toUpperCase() + x.slice(1).toLowerCase()) 7 | .join(''); 8 | return s.slice(0, 1).toLowerCase() + s.slice(1); 9 | }; -------------------------------------------------------------------------------- /snippets/average.zh.md: -------------------------------------------------------------------------------- 1 | ### 平均 2 | 3 | 返回两个或更多个数字的平均值. 4 | 5 | 使用`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`,除以`长度`的数组. 6 | 7 | ```js 8 | const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length; 9 | ``` 10 | 11 | ```js 12 | average(...[1, 2, 3]); // 2 13 | average(1, 2, 3); // 2 14 | ``` -------------------------------------------------------------------------------- /snippets/countOccurrences.zh.md: -------------------------------------------------------------------------------- 1 | ### countoccurrences 2 | 3 | 统计数组中某个值的出现次数. 4 | 5 | 使用`array.reduce()`每次遇到数组中的特定值时增加一个计数器. 6 | 7 | ```js 8 | const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0); 9 | ``` 10 | 11 | ```js 12 | countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 13 | ``` -------------------------------------------------------------------------------- /snippets/difference.zh.md: -------------------------------------------------------------------------------- 1 | ### 区别 2 | 3 | 返回两个数组之间的差异. 4 | 5 | 创建一个`组`从`b`,然后使用`array.filter()`上`一个`只保留不包含的值`b`. 6 | 7 | ```js 8 | const difference = (a, b) => { 9 | const s = new Set(b); 10 | return a.filter(x => !s.has(x)); 11 | }; 12 | ``` 13 | 14 | ```js 15 | difference([1, 2, 3], [1, 2, 4]); // [3] 16 | ``` -------------------------------------------------------------------------------- /snippets/dropRight.zh.md: -------------------------------------------------------------------------------- 1 | ### dropright 2 | 3 | 返回一个新的数组`ñ`元素从右侧移除. 4 | 5 | 使用`array.slice()`从右侧删除指定数量的元素. 6 | 7 | ```js 8 | const dropRight = (arr, n = 1) => arr.slice(0, -n); 9 | ``` 10 | 11 | ```js 12 | dropRight([1, 2, 3]); // [1,2] 13 | dropRight([1, 2, 3], 2); // [1] 14 | dropRight([1, 2, 3], 42); // [] 15 | ``` -------------------------------------------------------------------------------- /snippets/getType.zh.md: -------------------------------------------------------------------------------- 1 | ### 将gettype 2 | 3 | 返回值的本机类型. 4 | 5 | 返回小写的构造函数名称的值,`"不确定"`要么`"空值"`如果价值是`未定义`要么`空值`. 6 | 7 | ```js 8 | const getType = v => 9 | v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); 10 | ``` 11 | 12 | ```js 13 | getType(new Set([1, 2, 3])); // 'set' 14 | ``` -------------------------------------------------------------------------------- /snippets/hasClass.zh.md: -------------------------------------------------------------------------------- 1 | ### hasclass 2 | 3 | 回报`真正`如果元素具有指定的类,`假`除此以外. 4 | 5 | 使用`element.classlist.contains()`检查元素是否具有指定的类. 6 | 7 | ```js 8 | const hasClass = (el, className) => el.classList.contains(className); 9 | ``` 10 | 11 | ```js 12 | hasClass(document.querySelector('p.special'), 'special'); // true 13 | ``` -------------------------------------------------------------------------------- /snippets/hide.zh.md: -------------------------------------------------------------------------------- 1 | ### 隐藏 2 | 3 | 隐藏指定的所有元素. 4 | 5 | 使用扩展运算符(`...`)和`array.foreach()`申请`显示: 无`到每个指定的元素. 6 | 7 | ```js 8 | const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); 9 | ``` 10 | 11 | ```js 12 | hide(...document.querySelectorAll('img')); // Hides all elements on the page 13 | ``` -------------------------------------------------------------------------------- /test/anagrams/anagrams.js: -------------------------------------------------------------------------------- 1 | module.exports = anagrams = str => { 2 | if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str]; 3 | return str 4 | .split('') 5 | .reduce( 6 | (acc, letter, i) => 7 | acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), 8 | [] 9 | ); 10 | }; -------------------------------------------------------------------------------- /test/cleanObj/cleanObj.js: -------------------------------------------------------------------------------- 1 | module.exports = cleanObj = (obj, keysToKeep = [], childIndicator) => { 2 | Object.keys(obj).forEach(key => { 3 | if (key === childIndicator) { 4 | cleanObj(obj[key], keysToKeep, childIndicator); 5 | } else if (!keysToKeep.includes(key)) { 6 | delete obj[key]; 7 | } 8 | }); 9 | return obj; 10 | }; -------------------------------------------------------------------------------- /snippets/isLowerCase.zh.md: -------------------------------------------------------------------------------- 1 | ### islowercase 2 | 3 | 检查一个字符串是否小写. 4 | 5 | 将给定的字符串转换为小写,使用`string.tolowercase()`并与原来的比较. 6 | 7 | ```js 8 | const isLowerCase = str => str === str.toLowerCase(); 9 | ``` 10 | 11 | ```js 12 | isLowerCase('abc'); // true 13 | isLowerCase('a3@$'); // true 14 | isLowerCase('Ab4'); // false 15 | ``` -------------------------------------------------------------------------------- /snippets/isNull.md: -------------------------------------------------------------------------------- 1 | ### isNull 2 | 3 | Returns `true` if the specified value is `null`, `false` otherwise. 4 | 5 | Use the strict equality operator to check if the value and of `val` are equal to `null`. 6 | 7 | ```js 8 | const isNull = val => val === null; 9 | ``` 10 | 11 | ```js 12 | isNull(null); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/isNumber.md: -------------------------------------------------------------------------------- 1 | ### isNumber 2 | 3 | Checks if the given argument is a number. 4 | 5 | Use `typeof` to check if a value is classified as a number primitive. 6 | 7 | ```js 8 | const isNumber = val => typeof val === 'number'; 9 | ``` 10 | 11 | ```js 12 | isNumber('1'); // false 13 | isNumber(1); // true 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/isUpperCase.zh.md: -------------------------------------------------------------------------------- 1 | ### isuppercase 2 | 3 | 检查一个字符串是否为大写. 4 | 5 | 将给定的字符串转换为大写,使用`string.touppercase()`并与原来的比较. 6 | 7 | ```js 8 | const isUpperCase = str => str === str.toUpperCase(); 9 | ``` 10 | 11 | ```js 12 | isUpperCase('ABC'); // true 13 | isLowerCase('A3@$'); // true 14 | isLowerCase('aB4'); // false 15 | ``` -------------------------------------------------------------------------------- /snippets/toDecimalMark.zh.md: -------------------------------------------------------------------------------- 1 | ### todecimalmark 2 | 3 | 使用`的toLocaleString()`将浮点运算转换为[小数点](https://en.wikipedia.org/wiki/Decimal_mark)形成. 它使一个逗号分隔的字符串从一个数字. 4 | 5 | ```js 6 | const toDecimalMark = num => num.toLocaleString('en-US'); 7 | ``` 8 | 9 | ```js 10 | toDecimalMark(12305030388.9087); // "12,305,030,388.909" 11 | ``` -------------------------------------------------------------------------------- /snippets/without.zh.md: -------------------------------------------------------------------------------- 1 | ### 无 2 | 3 | 过滤出具有指定值之一的数组元素. 4 | 5 | 使用`array.filter()`创建一个数组排除(使用`!array.includes()`)所有给定的值. 6 | 7 | _(用于改变原始数组的细节请参阅[`拉`](#pull))_ 8 | 9 | ```js 10 | const without = (arr, ...args) => arr.filter(v => !args.includes(v)); 11 | ``` 12 | 13 | ```js 14 | without([2, 1, 2, 3], 1, 2); // [3] 15 | ``` -------------------------------------------------------------------------------- /test/pullAtValue/pullAtValue.js: -------------------------------------------------------------------------------- 1 | module.exports = pullAtValue = (arr, pullArr) => { 2 | let removed = [], 3 | pushToRemove = arr.forEach((v, i) => (pullArr.includes(v) ? removed.push(v) : v)), 4 | mutateTo = arr.filter((v, i) => !pullArr.includes(v)); 5 | arr.length = 0; 6 | mutateTo.forEach(v => arr.push(v)); 7 | return removed; 8 | }; -------------------------------------------------------------------------------- /snippets/escapeRegExp.md: -------------------------------------------------------------------------------- 1 | ### escapeRegExp 2 | 3 | Escapes a string to use in a regular expression. 4 | 5 | Use `String.replace()` to escape special characters. 6 | 7 | ```js 8 | const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); 9 | ``` 10 | 11 | ```js 12 | escapeRegExp('(test)'); // \\(test\\) 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/intersection.zh.md: -------------------------------------------------------------------------------- 1 | ### 路口 2 | 3 | 返回两个数组中存在的元素列表. 4 | 5 | 创建一个`组`从`b`,然后使用`array.filter()`上`一个`只保留包含的值`b`. 6 | 7 | ```js 8 | const intersection = (a, b) => { 9 | const s = new Set(b); 10 | return a.filter(x => s.has(x)); 11 | }; 12 | ``` 13 | 14 | ```js 15 | intersection([1, 2, 3], [4, 3, 2]); // [2,3] 16 | ``` -------------------------------------------------------------------------------- /snippets/tomorrow.zh.md: -------------------------------------------------------------------------------- 1 | ### 明天 2 | 3 | 导致明天的date.use的字符串表示`新日期()`拿到今天的日子`86400000`秒(24小时),使用`date.toisostring()`将日期对象转换为字符串. 4 | 5 | ```js 6 | const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; 7 | ``` 8 | 9 | ```js 10 | tomorrow(); // 2017-12-27 (if current date is 2017-12-26) 11 | ``` -------------------------------------------------------------------------------- /test/pluralize/pluralize.js: -------------------------------------------------------------------------------- 1 | module.exports = pluralize = (val, word, plural = word + 's') => { 2 | const _pluralize = (num, word, plural = word + 's') => 3 | [1, -1].includes(Number(num)) ? word : plural; 4 | if (typeof val === 'object') return (num, word) => _pluralize(num, word, val[word]); 5 | return _pluralize(val, word, plural); 6 | }; -------------------------------------------------------------------------------- /snippets/distance.md: -------------------------------------------------------------------------------- 1 | ### distance 2 | 3 | Returns the distance between two points. 4 | 5 | Use `Math.hypot()` to calculate the Euclidean distance between two points. 6 | 7 | ```js 8 | const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0); 9 | ``` 10 | 11 | ```js 12 | distance(1, 1, 2, 3); // 2.23606797749979 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/initializeArrayWithValues.zh.md: -------------------------------------------------------------------------------- 1 | ### initializearraywithvalues 2 | 3 | 用指定的值初始化和填充数组. 4 | 5 | 使用`阵列(n)的`创建所需长度的数组,`填写(五)`以期望的价值填补它,你可以省略`VAL`使用默认值`0`. 6 | 7 | ```js 8 | const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); 9 | ``` 10 | 11 | ```js 12 | initializeArrayWithValues(5, 2); // [2,2,2,2,2] 13 | ``` -------------------------------------------------------------------------------- /snippets/sum.md: -------------------------------------------------------------------------------- 1 | ### sum 2 | 3 | Returns the sum of two or more numbers/arrays. 4 | 5 | Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`. 6 | 7 | ```js 8 | const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0); 9 | ``` 10 | 11 | ```js 12 | sum(...[1, 2, 3, 4]); // 10 13 | ``` 14 | -------------------------------------------------------------------------------- /test/orderBy/orderBy.js: -------------------------------------------------------------------------------- 1 | module.exports = orderBy = (arr, props, orders) => 2 | [...arr].sort((a, b) => 3 | props.reduce((acc, prop, i) => { 4 | if (acc === 0) { 5 | const [p1, p2] = orders && orders[i] === 'desc' ? [b[prop], a[prop]] : [a[prop], b[prop]]; 6 | acc = p1 > p2 ? 1 : p1 < p2 ? -1 : 0; 7 | } 8 | return acc; 9 | }, 0) 10 | ); -------------------------------------------------------------------------------- /test/primes/primes.js: -------------------------------------------------------------------------------- 1 | module.exports = primes = num => { 2 | let arr = Array.from({ length: num - 1 }).map((x, i) => i + 2), 3 | sqroot = Math.floor(Math.sqrt(num)), 4 | numsTillSqroot = Array.from({ length: sqroot - 1 }).map((x, i) => i + 2); 5 | numsTillSqroot.forEach(x => (arr = arr.filter(y => y % x !== 0 || y == x))); 6 | return arr; 7 | }; -------------------------------------------------------------------------------- /snippets/clampNumber.zh.md: -------------------------------------------------------------------------------- 1 | ### clampnumber 2 | 3 | 夹子`NUM`在由边界值规定的包含范围内`一个`和`b`. 4 | 5 | 如果`NUM`属于范围之内,归还`NUM`. 另外,返回范围内最近的数字. 6 | 7 | ```js 8 | const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); 9 | ``` 10 | 11 | ```js 12 | clampNumber(2, 3, 5); // 3 13 | clampNumber(1, -1, -5); // -1 14 | ``` -------------------------------------------------------------------------------- /snippets/hammingDistance.zh.md: -------------------------------------------------------------------------------- 1 | ### 汉明距离 2 | 3 | 计算两个值之间的汉明距离. 4 | 5 | 使用xor运算符(`^`)来查找这两个数字之间的位差,使用转换为二进制字符串`的ToString(2)`.count和返回的数量`1`在字符串中,使用`匹配(/ 1 /克)`. 6 | 7 | ```js 8 | const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) ƜƜ '').length; 9 | ``` 10 | 11 | ```js 12 | hammingDistance(2, 3); // 1 13 | ``` -------------------------------------------------------------------------------- /snippets/negate.md: -------------------------------------------------------------------------------- 1 | ### negate 2 | 3 | Negates a predicate function. 4 | 5 | Take a predicate function and apply the not operator (`!`) to it with its arguments. 6 | 7 | ```js 8 | const negate = func => (...args) => !func(...args); 9 | ``` 10 | 11 | ```js 12 | [1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 == 0)); // [ 1, 3, 5 ] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/randomIntegerInRange.zh.md: -------------------------------------------------------------------------------- 1 | ### randomintegerinrange 2 | 3 | 返回指定范围内的随机整数. 4 | 5 | 使用`的Math.random()`生成一个随机数并将其映射到期望的范围,使用`math.floor()`使其成为一个整数. 6 | 7 | ```js 8 | const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; 9 | ``` 10 | 11 | ```js 12 | randomIntegerInRange(0, 5); // 2 13 | ``` -------------------------------------------------------------------------------- /snippets/validateNumber.zh.md: -------------------------------------------------------------------------------- 1 | ### validatenumber 2 | 3 | 回报`真正`如果给定的值是一个数字,`假`除此以外. 4 | 5 | 使用`!isnan()`与...结合`parsefloat()`检查参数是否是一个数字`ISFINITE()`检查数量是否有限`数()`检查强制是否成立. 6 | 7 | ```js 8 | const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; 9 | ``` 10 | 11 | ```js 12 | validateNumber('10'); // true 13 | ``` -------------------------------------------------------------------------------- /snippets/RGBToHex.zh.md: -------------------------------------------------------------------------------- 1 | ### rgbtohex 2 | 3 | 将rgb组件的值转换为颜色代码. 4 | 5 | 使用按位左移运算符将给定的rgb参数转换为十六进制字符串(`<<`)和`的ToString(16)`, 然后`string.padstart(6, '0')`得到一个6位的十六进制值. 6 | 7 | ```js 8 | const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); 9 | ``` 10 | 11 | ```js 12 | RGBToHex(255, 165, 1); // 'ffa501' 13 | ``` -------------------------------------------------------------------------------- /snippets/deepFlatten.zh.md: -------------------------------------------------------------------------------- 1 | ### deepflatten 2 | 3 | 深沉的阵列. 4 | 5 | 使用递归.use`array.concat()`用一个空数组(`[]`)和传播运算符(`...`)来扁平化一个数组. 递归地扁平化每个元素是一个数组. 6 | 7 | ```js 8 | const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); 9 | ``` 10 | 11 | ```js 12 | deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] 13 | ``` -------------------------------------------------------------------------------- /snippets/isFunction.md: -------------------------------------------------------------------------------- 1 | ### isFunction 2 | 3 | Checks if the given argument is a function. 4 | 5 | Use `typeof` to check if a value is classified as a function primitive. 6 | 7 | ```js 8 | const isFunction = val => typeof val === 'function'; 9 | ``` 10 | 11 | ```js 12 | isFunction('x'); // false 13 | isFunction(x => x); // true 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/serializeCookie.zh.md: -------------------------------------------------------------------------------- 1 | ### serializecookie 2 | 3 | 将一个cookie名称 - 值对序列化为一个set-cookie头字符串. 4 | 5 | 使用模板文字和`encodeURIComponent方法()`创建适当的字符串. 6 | 7 | ```js 8 | const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; 9 | ``` 10 | 11 | ```js 12 | serializeCookie('foo', 'bar'); // 'foo=bar' 13 | ``` -------------------------------------------------------------------------------- /snippets/union.md: -------------------------------------------------------------------------------- 1 | ### union 2 | 3 | Returns every element that exists in any of the two arrays once. 4 | 5 | Create a `Set` with all values of `a` and `b` and convert to an array. 6 | 7 | ```js 8 | const union = (a, b) => Array.from(new Set([...a, ...b])); 9 | ``` 10 | 11 | ```js 12 | union([1, 2, 3], [4, 3, 2]); // [1,2,3,4] 13 | ``` 14 | -------------------------------------------------------------------------------- /test/binarySearch/binarySearch.js: -------------------------------------------------------------------------------- 1 | module.exports = binarySearch = (arr, val, start = 0, end = arr.length - 1) => { 2 | if (start > end) return -1; 3 | const mid = Math.floor((start + end) / 2); 4 | if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1); 5 | if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end); 6 | return mid; 7 | } -------------------------------------------------------------------------------- /test/luhnCheck/luhnCheck.js: -------------------------------------------------------------------------------- 1 | module.exports = luhnCheck = num => { 2 | let arr = (num + '') 3 | .split('') 4 | .reverse() 5 | .map(x => parseInt(x)); 6 | let lastDigit = arr.splice(0, 1)[0]; 7 | let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + (val * 2) % 9 || 9), 0); 8 | sum += lastDigit; 9 | return sum % 10 === 0; 10 | }; -------------------------------------------------------------------------------- /snippets/cloneRegExp.zh.md: -------------------------------------------------------------------------------- 1 | ### cloneregexp 2 | 3 | 克隆一个正则表达式. 4 | 5 | 使用`新的正则表达式()`,`regexp.source`和`regexp.flags`克隆给定的正则表达式. 6 | 7 | ```js 8 | const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); 9 | ``` 10 | 11 | ```js 12 | const regExp = /lorem ipsum/gi; 13 | const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi 14 | ``` -------------------------------------------------------------------------------- /snippets/isBoolean.md: -------------------------------------------------------------------------------- 1 | ### isBoolean 2 | 3 | Checks if the given argument is a native boolean element. 4 | 5 | Use `typeof` to check if a value is classified as a boolean primitive. 6 | 7 | ```js 8 | const isBoolean = val => typeof val === 'boolean'; 9 | ``` 10 | 11 | ```js 12 | isBoolean(null); // false 13 | isBoolean(false); // true 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/truncateString.zh.md: -------------------------------------------------------------------------------- 1 | ### truncatestring 2 | 3 | 截断一个字符串到指定的长度. 4 | 5 | 确定字符串的`长度`大于`NUM`. 将字符串截断为所需的长度`'...'`追加到最后或原始字符串. 6 | 7 | ```js 8 | const truncateString = (str, num) => 9 | str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; 10 | ``` 11 | 12 | ```js 13 | truncateString('boomerang', 7); // 'boom...' 14 | ``` -------------------------------------------------------------------------------- /test/standardDeviation/standardDeviation.js: -------------------------------------------------------------------------------- 1 | module.exports = standardDeviation = (arr, usePopulation = false) => { 2 | const mean = arr.reduce((acc, val) => acc + val, 0) / arr.length; 3 | return Math.sqrt( 4 | arr.reduce((acc, val) => acc.concat((val - mean) ** 2), []).reduce((acc, val) => acc + val, 0) / 5 | (arr.length - (usePopulation ? 0 : 1)) 6 | ); 7 | }; -------------------------------------------------------------------------------- /snippets/capitalizeEveryWord.zh.md: -------------------------------------------------------------------------------- 1 | ### capitalizeeveryword 2 | 3 | 大写字符串中每个单词的第一个字母. 4 | 5 | 使用`与string.replace()`匹配每个单词的第一个字符`string.touppercase()`将其资本化. 6 | 7 | ```js 8 | const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); 9 | ``` 10 | 11 | ```js 12 | capitalizeEveryWord('hello world!'); // 'Hello World!' 13 | ``` -------------------------------------------------------------------------------- /snippets/isDivisible.md: -------------------------------------------------------------------------------- 1 | ### isDivisible 2 | 3 | Checks if the first numeric argument is divisible by the second one. 4 | 5 | Use the modulo operator (`%`) to check if the remainder is equal to `0`. 6 | 7 | ```js 8 | const isDivisible = (dividend, divisor) => dividend % divisor === 0; 9 | ``` 10 | 11 | ```js 12 | isDivisible(6, 3); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/pick.zh.md: -------------------------------------------------------------------------------- 1 | ### 挑 2 | 3 | 从对象中选择与给定键对应的键值对. 4 | 5 | 使用`array.reduce()`如果密钥存在于obj中,则将过滤/拾取的密钥转换回具有对应的密钥 - 值对的对象. 6 | 7 | ```js 8 | const pick = (obj, arr) => 9 | arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); 10 | ``` 11 | 12 | ```js 13 | pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 } 14 | ``` -------------------------------------------------------------------------------- /snippets/coalesce.md: -------------------------------------------------------------------------------- 1 | ### coalesce 2 | 3 | Returns the first non-null/undefined argument. 4 | 5 | Use `Array.find()` to return the first non `null`/`undefined` argument. 6 | 7 | ```js 8 | const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_)); 9 | ``` 10 | 11 | ```js 12 | coalesce(null, undefined, '', NaN, 'Waldo'); // "" 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/toggleClass.zh.md: -------------------------------------------------------------------------------- 1 | ### toggleclass 2 | 3 | 切换一个元素的类. 4 | 5 | 使用`element.classlist.toggle()`为元素切换指定的类. 6 | 7 | ```js 8 | const toggleClass = (el, className) => el.classList.toggle(className); 9 | ``` 10 | 11 | ```js 12 | toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore 13 | ``` -------------------------------------------------------------------------------- /snippets/everyNth.md: -------------------------------------------------------------------------------- 1 | ### everyNth 2 | 3 | Returns every nth element in an array. 4 | 5 | Use `Array.filter()` to create a new array that contains every nth element of a given array. 6 | 7 | ```js 8 | const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1); 9 | ``` 10 | 11 | ```js 12 | everyNth([1, 2, 3, 4, 5, 6], 2); // [ 2, 4, 6 ] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/setStyle.zh.md: -------------------------------------------------------------------------------- 1 | ### 的setStyle 2 | 3 | 为指定的元素设置一个css规则的值. 4 | 5 | 使用`element.style`将指定元素的css规则的值设置为`VAL`. 6 | 7 | ```js 8 | const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); 9 | ``` 10 | 11 | ```js 12 | setStyle(document.querySelector('p'), 'font-size', '20px'); // The first

    element on the page will have a font-size of 20px 13 | ``` -------------------------------------------------------------------------------- /snippets_archive/removeVowels.zh.md: -------------------------------------------------------------------------------- 1 | ### removevowels 2 | 3 | 返回a中的所有元音`海峡`取而代之`REPL`. 4 | 5 | 使用`与string.replace()`用正则表达式来替换所有的元音`海峡`.omot`REPL`使用默认值`""`. 6 | 7 | ```js 8 | const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); 9 | ``` 10 | 11 | ```js 12 | removeVowels("foobAr"); // "fbr" 13 | removeVowels("foobAr","*"); // "f**b*r" 14 | ``` -------------------------------------------------------------------------------- /test/httpPut/httpPut.js: -------------------------------------------------------------------------------- 1 | module.exports = httpPut = (url, data, callback, err = console.error) => { 2 | const request = new XMLHttpRequest(); 3 | request.open("PUT", url, true); 4 | request.setRequestHeader('Content-type','application/json; charset=utf-8'); 5 | request.onload = () => callback(request); 6 | request.onerror = () => err(request); 7 | request.send(data); 8 | }; -------------------------------------------------------------------------------- /snippets/nthElement.zh.md: -------------------------------------------------------------------------------- 1 | ### nthelement 2 | 3 | 返回数组的第n个元素. 4 | 5 | 使用`array.slice()`得到一个包含第n个元素的数组. 如果索引超出范围,则返回`[]`. 第二个参数,`ñ`,得到数组的第一个元素. 6 | 7 | ```js 8 | const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; 9 | ``` 10 | 11 | ```js 12 | nthElement(['a', 'b', 'c'], 1); // 'b' 13 | nthElement(['a', 'b', 'b'], -3); // 'a' 14 | ``` -------------------------------------------------------------------------------- /snippets/objectFromPairs.md: -------------------------------------------------------------------------------- 1 | ### objectFromPairs 2 | 3 | Creates an object from the given key-value pairs. 4 | 5 | Use `Array.reduce()` to create and combine key-value pairs. 6 | 7 | ```js 8 | const objectFromPairs = arr => arr.reduce((a, v) => ((a[v[0]] = v[1]), a), {}); 9 | ``` 10 | 11 | ```js 12 | objectFromPairs([['a', 1], ['b', 2]]); // {a: 1, b: 2} 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/redirect.zh.md: -------------------------------------------------------------------------------- 1 | ### 重定向 2 | 3 | 重定向到指定的网址. 4 | 5 | 使用`window.location.href`要么`window.location.replace()`重定向到`网址`. 传递第二个参数来模拟链接点击(`真正`- 默认)或http重定向`假`). 6 | 7 | ```js 8 | const redirect = (url, asLink = true) => 9 | asLink ? (window.location.href = url) : window.location.replace(url); 10 | ``` 11 | 12 | ```js 13 | redirect('https://google.com'); 14 | ``` -------------------------------------------------------------------------------- /snippets/tail.md: -------------------------------------------------------------------------------- 1 | ### tail 2 | 3 | Returns all elements in an array except for the first one. 4 | 5 | Return `Array.slice(1)` if the array's `length` is more than `1`, otherwise, return the whole array. 6 | 7 | ```js 8 | const tail = arr => (arr.length > 1 ? arr.slice(1) : arr); 9 | ``` 10 | 11 | ```js 12 | tail([1, 2, 3]); // [2,3] 13 | tail([1]); // [1] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/take.md: -------------------------------------------------------------------------------- 1 | ### take 2 | 3 | Returns an array with n elements removed from the beginning. 4 | 5 | Use `Array.slice()` to create a slice of the array with `n` elements taken from the beginning. 6 | 7 | ```js 8 | const take = (arr, n = 1) => arr.slice(0, n); 9 | ``` 10 | 11 | ```js 12 | take([1, 2, 3], 5); // [1, 2, 3] 13 | take([1, 2, 3], 0); // [] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets_archive/fibonacciCountUntilNum.zh.md: -------------------------------------------------------------------------------- 1 | ### fibonaccicountuntilnum 2 | 3 | 返回斐波纳契数字的数量`NUM`(`0`和`NUM`包括的). 4 | 5 | 用一个数学公式来计算斐波那契数的数量直到`NUM`. 6 | 7 | ```js 8 | const fibonacciCountUntilNum = num => 9 | Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); 10 | ``` 11 | 12 | ```js 13 | fibonacciCountUntilNum(10); // 7 14 | ``` -------------------------------------------------------------------------------- /snippets/byteSize.md: -------------------------------------------------------------------------------- 1 | ### byteSize 2 | 3 | Returns the length of a string in bytes. 4 | 5 | Convert a given string to a [`Blob` Object](https://developer.mozilla.org/en-US/docs/Web/API/Blob) and find its `size`. 6 | 7 | ```js 8 | const byteSize = str => new Blob([str]).size; 9 | ``` 10 | 11 | ```js 12 | byteSize('😀'); // 4 13 | byteSize('Hello World'); // 11 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/distinctValuesOfArray.md: -------------------------------------------------------------------------------- 1 | ### distinctValuesOfArray 2 | 3 | Returns all the distinct values of an array. 4 | 5 | Use ES6 `Set` and the `...rest` operator to discard all duplicated values. 6 | 7 | ```js 8 | const distinctValuesOfArray = arr => [...new Set(arr)]; 9 | ``` 10 | 11 | ```js 12 | distinctValuesOfArray([1, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/getDaysDiffBetweenDates.zh.md: -------------------------------------------------------------------------------- 1 | ### getdaysdiffbetweendates 2 | 3 | 返回两个日期之间的差异(以天计). 4 | 5 | 计算两者之间的差异(以天计)`日期`对象. 6 | 7 | ```js 8 | const getDaysDiffBetweenDates = (dateInitial, dateFinal) => 9 | (dateFinal - dateInitial) / (1000 * 3600 * 24); 10 | ``` 11 | 12 | ```js 13 | getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 14 | ``` -------------------------------------------------------------------------------- /snippets/isEven.md: -------------------------------------------------------------------------------- 1 | ### isEven 2 | 3 | Returns `true` if the given number is even, `false` otherwise. 4 | 5 | Checks whether a number is odd or even using the modulo (`%`) operator. 6 | Returns `true` if the number is even, `false` if the number is odd. 7 | 8 | ```js 9 | const isEven = num => num % 2 === 0; 10 | ``` 11 | 12 | ```js 13 | isEven(3); // false 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/percentile.zh.md: -------------------------------------------------------------------------------- 1 | ### 百分 2 | 3 | 使用百分比公式来计算给定数组中有多少数字小于或等于给定值. 4 | 5 | 使用`array.reduce()`计算有多少数值低于这个值,有多少是相同的值,并应用百分比公式. 6 | 7 | ```js 8 | const percentile = (arr, val) => 9 | 100 * arr.reduce((acc, v) => acc + (v < val ? 1 : 0) + (v === val ? 0.5 : 0), 0) / arr.length; 10 | ``` 11 | 12 | ```js 13 | percentile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 6); // 55 14 | ``` -------------------------------------------------------------------------------- /snippets/shallowClone.md: -------------------------------------------------------------------------------- 1 | ### shallowClone 2 | 3 | Creates a shallow clone of an object. 4 | 5 | Use `Object.assign()` and an empty object (`{}`) to create a shallow clone of the original. 6 | 7 | ```js 8 | const shallowClone = obj => Object.assign({}, obj); 9 | ``` 10 | 11 | ```js 12 | const a = { x: true, y: 1 }; 13 | const b = shallowClone(a); // a !== b 14 | ``` 15 | -------------------------------------------------------------------------------- /docs/clipboard.svg: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /snippets/filterNonUnique.md: -------------------------------------------------------------------------------- 1 | ### filterNonUnique 2 | 3 | Filters out the non-unique values in an array. 4 | 5 | Use `Array.filter()` for an array containing only the unique values. 6 | 7 | ```js 8 | const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i)); 9 | ``` 10 | 11 | ```js 12 | filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1,3,5] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/isAbsoluteURL.zh.md: -------------------------------------------------------------------------------- 1 | ### isabsoluteurl 2 | 3 | 回报`真正`如果给定的字符串是一个绝对的url,`假`除此以外. 4 | 5 | 使用正则表达式来测试字符串是否是绝对url. 6 | 7 | ```js 8 | const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); 9 | ``` 10 | 11 | ```js 12 | isAbsoluteURL('https://google.com'); // true 13 | isAbsoluteURL('ftp://www.myserver.net'); // true 14 | isAbsoluteURL('/foo/bar'); // false 15 | ``` -------------------------------------------------------------------------------- /snippets/sleep.zh.md: -------------------------------------------------------------------------------- 1 | ### 睡觉 2 | 3 | 延迟异步函数的执行. 4 | 5 | 延迟执行的一部分`异步`功能,通过把它睡觉,返回一个`诺言`. 6 | 7 | ```js 8 | const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); 9 | ``` 10 | 11 | ```js 12 | async function sleepyWork() { 13 | console.log("I'm going to sleep for 1 second."); 14 | await sleep(1000); 15 | console.log('I woke up after 1 second.'); 16 | } 17 | ``` -------------------------------------------------------------------------------- /snippets/compact.md: -------------------------------------------------------------------------------- 1 | ### compact 2 | 3 | Removes falsey values from an array. 4 | 5 | Use `Array.filter()` to filter out falsey values (`false`, `null`, `0`, `""`, `undefined`, and `NaN`). 6 | 7 | ```js 8 | const compact = arr => arr.filter(Boolean); 9 | ``` 10 | 11 | ```js 12 | compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); // [ 1, 2, 3, 'a', 's', 34 ] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/initialize2DArray.zh.md: -------------------------------------------------------------------------------- 1 | ### initialize2darray 2 | 3 | 初始化一个给定的宽度和高度和值的二维数组. 4 | 5 | 使用`array.map()`生成h行,其中每个行都是一个新的数组w,用值初始化. `如果没有提供该值,则默认为`空值. 6 | 7 | ```js 8 | const initialize2DArray = (w, h, val = null) => 9 | Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); 10 | ``` 11 | 12 | ```js 13 | initialize2DArray(2, 2, 0); // [[0,0], [0,0]] 14 | ``` -------------------------------------------------------------------------------- /snippets/isPrime.zh.md: -------------------------------------------------------------------------------- 1 | ### isprime 2 | 3 | 检查提供的整数是否是素数. 4 | 5 | 检查数字`2`给定数字的平方根`假`如果他们中的任何一个除以给定的数字,否则返回`真正`,除非数字少于`2`. 6 | 7 | ```js 8 | const isPrime = num => { 9 | const boundary = Math.floor(Math.sqrt(num)); 10 | for (var i = 2; i <= boundary; i++) if (num % i == 0) return false; 11 | return num >= 2; 12 | }; 13 | ``` 14 | 15 | ```js 16 | isPrime(11); // true 17 | ``` -------------------------------------------------------------------------------- /snippets/sortCharactersInString.zh.md: -------------------------------------------------------------------------------- 1 | ### sortcharactersinstring 2 | 3 | 按字母顺序排列字符串中的字符. 4 | 5 | 使用扩展运算符(`...`)`中的Array.sort()`和`string.localecompare()`排序中的字符`海峡`,使用重组`的string.join( '')`. 6 | 7 | ```js 8 | const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); 9 | ``` 10 | 11 | ```js 12 | sortCharactersInString('cabbage'); // 'aabbceg' 13 | ``` -------------------------------------------------------------------------------- /snippets_archive/countVowels.md: -------------------------------------------------------------------------------- 1 | ### countVowels 2 | 3 | Retuns `number` of vowels in provided string. 4 | 5 | Use a regular expression to count the number of vowels `(A, E, I, O, U)` in a `string`. 6 | 7 | ```js 8 | const countVowels = str => (str.match(/[aeiou]/gi) || []).length; 9 | ``` 10 | 11 | ```js 12 | countVowels('foobar'); // 3 13 | countVowels('gym'); // 0 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/getStyle.md: -------------------------------------------------------------------------------- 1 | ### getStyle 2 | 3 | Returns the value of a CSS rule for the specified element. 4 | 5 | Use `Window.getComputedStyle()` to get the value of the CSS rule for the specified element. 6 | 7 | ```js 8 | const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName]; 9 | ``` 10 | 11 | ```js 12 | getStyle(document.querySelector('p'), 'font-size'); // '16px' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/maxN.zh.md: -------------------------------------------------------------------------------- 1 | ### MAXN 2 | 3 | 返回`ñ`提供的数组中的最大元素. `如果`ñ 4 | 5 | 大于或等于提供的数组长度,则返回原始数组(按降序排列). `使用`中的Array.sort()`结合传播算子(`...`)创建一个数组的浅层克隆,并按降序排列.use`array.slice()`获取指定数量的元素. 试试第二个参数,`ñ,得到一个元素的数组. 6 | 7 | ```js 8 | const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n); 9 | ``` 10 | 11 | ```js 12 | maxN([1, 2, 3]); // [3] 13 | maxN([1, 2, 3], 2); // [3,2] 14 | ``` -------------------------------------------------------------------------------- /snippets/minN.zh.md: -------------------------------------------------------------------------------- 1 | ### 明尼苏达州 2 | 3 | 返回`ñ`来自提供的数组的最小元素. `如果`ñ 4 | 5 | 大于或等于提供的数组长度,则返回原始数组(按升序排序). `使用`中的Array.sort()`结合传播算子(`...`)创建数组的浅层克隆,并按升序对其进行排序`array.slice()`获取指定数量的元素. 试试第二个参数,`ñ,得到一个元素的数组. 6 | 7 | ```js 8 | const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n); 9 | ``` 10 | 11 | ```js 12 | minN([1, 2, 3]); // [1] 13 | minN([1, 2, 3], 2); // [1,2] 14 | ``` -------------------------------------------------------------------------------- /test/httpPost/httpPost.js: -------------------------------------------------------------------------------- 1 | module.exports = httpPost = (url, callback, data = null, err = console.error) => { 2 | const request = new XMLHttpRequest(); 3 | request.open('POST', url, true); 4 | request.setRequestHeader('Content-type', 'application/json; charset=utf-8'); 5 | request.onload = () => callback(request.responseText); 6 | request.onerror = () => err(request); 7 | request.send(data); 8 | }; -------------------------------------------------------------------------------- /snippets/differenceWith.zh.md: -------------------------------------------------------------------------------- 1 | ### differencewith 2 | 3 | 滤除比较函数不返回的数组中的所有值`真正`. 4 | 5 | 使用`array.filter()`和`array.findindex()`找到合适的值. 6 | 7 | ```js 8 | const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); 9 | ``` 10 | 11 | ```js 12 | differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2] 13 | ``` -------------------------------------------------------------------------------- /snippets/dropElements.zh.md: -------------------------------------------------------------------------------- 1 | ### dropelements 2 | 3 | 删除数组中的元素,直到传递的函数返回`真正`. 4 | 5 | 返回数组中的其余元素. `循环遍历数组,使用`array.slice()`删除数组的第一个元素,直到函数的返回值为止`真正回收剩余的元素. 6 | 7 | ```js 8 | const dropElements = (arr, func) => { 9 | while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1); 10 | return arr; 11 | }; 12 | ``` 13 | 14 | ```js 15 | dropElements([1, 2, 3, 4], n => n >= 3); // [3,4] 16 | ``` -------------------------------------------------------------------------------- /snippets/factorial.zh.md: -------------------------------------------------------------------------------- 1 | ### 阶乘 2 | 3 | 计算一个数的阶乘. 4 | 5 | 使用递归.if`ñ`小于或等于`1`,返回`1`. 其他,退货的产品`ñ`和阶乘`n - 1`. 如果发生异常`ñ`是一个负数. 6 | 7 | ```js 8 | const factorial = n => 9 | n < 0 10 | ? (() => { 11 | throw new TypeError('Negative numbers are not allowed!'); 12 | })() 13 | : n <= 1 ? 1 : n * factorial(n - 1); 14 | ``` 15 | 16 | ```js 17 | factorial(6); // 720 18 | ``` -------------------------------------------------------------------------------- /snippets/similarity.md: -------------------------------------------------------------------------------- 1 | ### similarity 2 | 3 | Returns an array of elements that appear in both arrays. 4 | 5 | Use `Array.filter()` to remove values that are not part of `values`, determined using `Array.includes()`. 6 | 7 | ```js 8 | const similarity = (arr, values) => arr.filter(v => values.includes(v)); 9 | ``` 10 | 11 | ```js 12 | similarity([1, 2, 3], [1, 2, 4]); // [1,2] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/splitLines.md: -------------------------------------------------------------------------------- 1 | ### splitLines 2 | 3 | Splits a multiline string into an array of lines. 4 | 5 | Use `String.split()` and a regular expression to match line breaks and create an array. 6 | 7 | ```js 8 | const splitLines = str => str.split(/\r?\n/); 9 | ``` 10 | 11 | ```js 12 | splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , ''] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/toSafeInteger.zh.md: -------------------------------------------------------------------------------- 1 | ### tosafeinteger 2 | 3 | 将一个值转换为一个安全的整数. 4 | 5 | 使用`math.max()`和`math.min()`找到最接近的安全值`math.round()`转换为一个整数. 6 | 7 | ```js 8 | const toSafeInteger = num => 9 | Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); 10 | ``` 11 | 12 | ```js 13 | toSafeInteger('3.2'); // 3 14 | toSafeInteger(Infinity); // 9007199254740991 15 | ``` -------------------------------------------------------------------------------- /snippets/digitize.md: -------------------------------------------------------------------------------- 1 | ### digitize 2 | 3 | Converts a number to an array of digits. 4 | 5 | Convert the number to a string, using the spread operator (`...`) to build an array. 6 | Use `Array.map()` and `parseInt()` to transform each value to an integer. 7 | 8 | ```js 9 | const digitize = n => [...`${n}`].map(i => parseInt(i)); 10 | ``` 11 | 12 | ```js 13 | digitize(123); // [1, 2, 3] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/gcd.zh.md: -------------------------------------------------------------------------------- 1 | ### GCD 2 | 3 | 计算两个或更多数字/数组之间的最大公约数. 4 | 5 | 内在`_gcd`函数使用recursion.base的情况是什么时候`ÿ`等于`0`. `在这种情况下,返回`X`其他的,返回gcd的`ÿ`和其余的部门`x / y的. 6 | 7 | ```js 8 | const gcd = (...arr) => { 9 | const _gcd = (x, y) => (!y ? x : gcd(y, x % y)); 10 | return [...arr].reduce((a, b) => _gcd(a, b)); 11 | }; 12 | ``` 13 | 14 | ```js 15 | gcd(8, 36); // 4 16 | gcd(...[12, 8, 32]); // 4 17 | ``` -------------------------------------------------------------------------------- /snippets/hide.md: -------------------------------------------------------------------------------- 1 | ### hide 2 | 3 | Hides all the elements specified. 4 | 5 | Use the spread operator (`...`) and `Array.forEach()` to apply `display: none` to each element specified. 6 | 7 | ```js 8 | const hide = (...el) => [...el].forEach(e => (e.style.display = 'none')); 9 | ``` 10 | 11 | ```js 12 | hide(...document.querySelectorAll('img')); // Hides all elements on the page 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/takeRight.md: -------------------------------------------------------------------------------- 1 | ### takeRight 2 | 3 | Returns an array with n elements removed from the end. 4 | 5 | Use `Array.slice()` to create a slice of the array with `n` elements taken from the end. 6 | 7 | ```js 8 | const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length); 9 | ``` 10 | 11 | ```js 12 | takeRight([1, 2, 3], 2); // [ 2, 3 ] 13 | takeRight([1, 2, 3]); // [3] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets_archive/JSONToDate.zh.md: -------------------------------------------------------------------------------- 1 | ### jsontodate 2 | 3 | 将json对象转换为日期. 4 | 5 | 使用`日期()`,将json格式的日期转换为可读的格式(`日/月/年`). 6 | 7 | ```js 8 | const JSONToDate = arr => { 9 | const dt = new Date(parseInt(arr.toString().substr(6))); 10 | return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; 11 | }; 12 | ``` 13 | 14 | ```js 15 | JSONToDate(/Date(1489525200000)/); // "14/3/2017" 16 | ``` -------------------------------------------------------------------------------- /snippets/arrayToHtmlList.zh.md: -------------------------------------------------------------------------------- 1 | ### arraytohtmllist 2 | 3 | 将给定的数组元素转换成`

  • `标签并将其附加到给定ID的列表中. 4 | 5 | 使用`array.map()`和`document.queryselector()`创建一个html标签列表. 6 | 7 | ```js 8 | const arrayToHtmlList = (arr, listID) => 9 | arr.map(item => (document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `)); 10 | ``` 11 | 12 | ```js 13 | arrayToHtmlList(['item 1', 'item 2'], 'myListID'); 14 | ``` -------------------------------------------------------------------------------- /snippets/cloneRegExp.md: -------------------------------------------------------------------------------- 1 | ### cloneRegExp 2 | 3 | Clones a regular expression. 4 | 5 | Use `new RegExp()`, `RegExp.source` and `RegExp.flags` to clone the given regular expression. 6 | 7 | ```js 8 | const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags); 9 | ``` 10 | 11 | ```js 12 | const regExp = /lorem ipsum/gi; 13 | const regExp2 = cloneRegExp(regExp); // /lorem ipsum/gi 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/fibonacci.zh.md: -------------------------------------------------------------------------------- 1 | ### 斐波那契 2 | 3 | 生成一个包含斐波那契数列的数组,直到第n项. 4 | 5 | 创建一个特定长度的空数组,初始化前两个值(`0`和`1`). 使用`array.reduce()`使用最后两个值的总和将值添加到数组中,除了前两个值之外. 6 | 7 | ```js 8 | const fibonacci = n => 9 | Array.from({ length: n }).reduce( 10 | (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i), 11 | [] 12 | ); 13 | ``` 14 | 15 | ```js 16 | fibonacci(6); // [0, 1, 1, 2, 3, 5] 17 | ``` -------------------------------------------------------------------------------- /snippets/functionName.md: -------------------------------------------------------------------------------- 1 | ### functionName 2 | 3 | Logs the name of a function. 4 | 5 | Use `console.debug()` and the `name` property of the passed method to log the method's name to the `debug` channel of the console. 6 | 7 | ```js 8 | const functionName = fn => (console.debug(fn.name), fn); 9 | ``` 10 | 11 | ```js 12 | functionName(Math.max); // max (logged in debug channel of console) 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/getType.md: -------------------------------------------------------------------------------- 1 | ### getType 2 | 3 | Returns the native type of a value. 4 | 5 | Returns lowercased constructor name of value, `"undefined"` or `"null"` if value is `undefined` or `null`. 6 | 7 | ```js 8 | const getType = v => 9 | v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase(); 10 | ``` 11 | 12 | ```js 13 | getType(new Set([1, 2, 3])); // 'set' 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/hasClass.md: -------------------------------------------------------------------------------- 1 | ### hasClass 2 | 3 | Returns `true` if the element has the specified class, `false` otherwise. 4 | 5 | Use `element.classList.contains()` to check if the element has the specified class. 6 | 7 | ```js 8 | const hasClass = (el, className) => el.classList.contains(className); 9 | ``` 10 | 11 | ```js 12 | hasClass(document.querySelector('p.special'), 'special'); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/invertKeyValues.zh.md: -------------------------------------------------------------------------------- 1 | ### invertkeyvalues 2 | 3 | 反转对象的键值对,而不会改变它. 4 | 5 | 使用`object.keys()`和`array.reduce()`反转对象的键值对. 6 | 7 | ```js 8 | const invertKeyValues = obj => 9 | Object.keys(obj).reduce((acc, key) => { 10 | acc[obj[key]] = key; 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' } 17 | ``` -------------------------------------------------------------------------------- /snippets/isLowerCase.md: -------------------------------------------------------------------------------- 1 | ### isLowerCase 2 | 3 | Checks if a string is lower case. 4 | 5 | Convert the given string to lower case, using `String.toLowerCase()` and compare it to the original. 6 | 7 | ```js 8 | const isLowerCase = str => str === str.toLowerCase(); 9 | ``` 10 | 11 | ```js 12 | isLowerCase('abc'); // true 13 | isLowerCase('a3@$'); // true 14 | isLowerCase('Ab4'); // false 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/randomNumberInRange.md: -------------------------------------------------------------------------------- 1 | ### randomNumberInRange 2 | 3 | Returns a random number in the specified range. 4 | 5 | Use `Math.random()` to generate a random value, map it to the desired range using multiplication. 6 | 7 | ```js 8 | const randomNumberInRange = (min, max) => Math.random() * (max - min) + min; 9 | ``` 10 | 11 | ```js 12 | randomNumberInRange(2, 10); // 6.0211363285087005 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/show.md: -------------------------------------------------------------------------------- 1 | ### show 2 | 3 | Shows all the elements specified. 4 | 5 | Use the spread operator (`...`) and `Array.forEach()` to clear the `display` property for each element specified. 6 | 7 | ```js 8 | const show = (...el) => [...el].forEach(e => (e.style.display = '')); 9 | ``` 10 | 11 | ```js 12 | show(...document.querySelectorAll('img')); // Shows all elements on the page 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/toDecimalMark.md: -------------------------------------------------------------------------------- 1 | ### toDecimalMark 2 | 3 | Use `toLocaleString()` to convert a float-point arithmetic to the [Decimal mark](https://en.wikipedia.org/wiki/Decimal_mark) form. It makes a comma separated string from a number. 4 | 5 | ```js 6 | const toDecimalMark = num => num.toLocaleString('en-US'); 7 | ``` 8 | 9 | ```js 10 | toDecimalMark(12305030388.9087); // "12,305,030,388.909" 11 | ``` 12 | -------------------------------------------------------------------------------- /snippets/bottomVisible.zh.md: -------------------------------------------------------------------------------- 1 | ### bottomvisible 2 | 3 | 回报`真正`如果页面底部可见,`假`除此以外. 4 | 5 | 使用`scrolly`,`scrollHeight属性`和`clientheight`以确定页面的底部是否可见. 6 | 7 | ```js 8 | const bottomVisible = () => 9 | document.documentElement.clientHeight + window.scrollY >= 10 | (document.documentElement.scrollHeight ƜƜ document.documentElement.clientHeight); 11 | ``` 12 | 13 | ```js 14 | bottomVisible(); // true 15 | ``` -------------------------------------------------------------------------------- /snippets/difference.md: -------------------------------------------------------------------------------- 1 | ### difference 2 | 3 | Returns the difference between two arrays. 4 | 5 | Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values not contained in `b`. 6 | 7 | ```js 8 | const difference = (a, b) => { 9 | const s = new Set(b); 10 | return a.filter(x => !s.has(x)); 11 | }; 12 | ``` 13 | 14 | ```js 15 | difference([1, 2, 3], [1, 2, 4]); // [3] 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets/isTravisCI.zh.md: -------------------------------------------------------------------------------- 1 | ### istravisci 2 | 3 | 检查当前的环境是否[travis ci](https://travis-ci.org/). 4 | 5 | 检查当前环境是否有`特拉维斯`和`CI`环境变量 ([参考](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)). 6 | 7 | ```js 8 | const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; 9 | ``` 10 | 11 | ```js 12 | isTravisCI(); // true (if code is running on Travis CI) 13 | ``` -------------------------------------------------------------------------------- /snippets/isUpperCase.md: -------------------------------------------------------------------------------- 1 | ### isUpperCase 2 | 3 | Checks if a string is upper case. 4 | 5 | Convert the given string to upper case, using `String.toUpperCase()` and compare it to the original. 6 | 7 | 8 | ```js 9 | const isUpperCase = str => str === str.toUpperCase(); 10 | ``` 11 | 12 | ```js 13 | isUpperCase('ABC'); // true 14 | isLowerCase('A3@$'); // true 15 | isLowerCase('aB4'); // false 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets/reverseString.md: -------------------------------------------------------------------------------- 1 | ### reverseString 2 | 3 | Reverses a string. 4 | 5 | Use the spread operator (`...`) and `Array.reverse()` to reverse the order of the characters in the string. 6 | Combine characters to get a string using `String.join('')`. 7 | 8 | ```js 9 | const reverseString = str => [...str].reverse().join(''); 10 | ``` 11 | 12 | ```js 13 | reverseString('foobar'); // 'raboof' 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/truthCheckCollection.zh.md: -------------------------------------------------------------------------------- 1 | ### truthcheckcollection 2 | 3 | 检查谓词(第二个参数)是否对集合的所有元素(第一个参数)是真实的. 4 | 5 | 使用`array.every()`检查每个通过的对象是否有指定的属性,如果它返回一个真值. 6 | 7 | ```js 8 | const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); 9 | ``` 10 | 11 | ```js 12 | truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true 13 | ``` -------------------------------------------------------------------------------- /test/toOrdinalSuffix/toOrdinalSuffix.js: -------------------------------------------------------------------------------- 1 | module.exports = toOrdinalSuffix = num => { 2 | const int = parseInt(num), 3 | digits = [int % 10, int % 100], 4 | ordinals = ['st', 'nd', 'rd', 'th'], 5 | oPattern = [1, 2, 3, 4], 6 | tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19]; 7 | return oPattern.includes(digits[0]) && !tPattern.includes(digits[1]) 8 | ? int + ordinals[digits[0] - 1] 9 | : int + ordinals[3]; 10 | }; -------------------------------------------------------------------------------- /snippets/compose.zh.md: -------------------------------------------------------------------------------- 1 | ### 撰写 2 | 3 | 执行从右到左的功能组合. 4 | 5 | 使用`array.reduce()`执行从右到左的函数组合. 最后(最右边的)函数可以接受一个或多个参数;其余的功能必须是一元的. 6 | 7 | ```js 8 | const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args))); 9 | ``` 10 | 11 | ```js 12 | const add5 = x => x + 5; 13 | const multiply = (x, y) => x * y; 14 | const multiplyAndAdd5 = compose(add5, multiply); 15 | multiplyAndAdd5(5, 2); // 15 16 | ``` -------------------------------------------------------------------------------- /snippets/findLast.md: -------------------------------------------------------------------------------- 1 | ### findLast 2 | 3 | Returns the last element for which the provided function returns a truthy value. 4 | 5 | Use `Array.filter()` to remove elements for which `fn` returns falsey values, `Array.slice(-1)` to get the last one. 6 | 7 | ```js 8 | const findLast = (arr, fn) => arr.filter(fn).slice(-1); 9 | ``` 10 | 11 | ```js 12 | findLast([1, 2, 3, 4], n => n % 2 === 1); // 3 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/forEachRight.zh.md: -------------------------------------------------------------------------------- 1 | ### foreachright 2 | 3 | 从数组的最后一个元素开始,为每个数组元素执行一次提供的函数. 4 | 5 | 使用`array.slice(0)`克隆给定的数组,`array.reverse()`扭转它和`array.foreach()`遍历倒排的数组. 6 | 7 | ```js 8 | const forEachRight = (arr, callback) => 9 | arr 10 | .slice(0) 11 | .reverse() 12 | .forEach(callback); 13 | ``` 14 | 15 | ```js 16 | forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' 17 | ``` -------------------------------------------------------------------------------- /snippets/maxBy.zh.md: -------------------------------------------------------------------------------- 1 | ### maxby 2 | 3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的最大值. 4 | 5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`math.max()`获得最大价值. 6 | 7 | ```js 8 | const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 9 | ``` 10 | 11 | ```js 12 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 13 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 14 | ``` -------------------------------------------------------------------------------- /snippets/minBy.zh.md: -------------------------------------------------------------------------------- 1 | ### minby 2 | 3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的最小值. 4 | 5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`math.min()`获得最大价值. 6 | 7 | ```js 8 | const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 9 | ``` 10 | 11 | ```js 12 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 13 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 14 | ``` -------------------------------------------------------------------------------- /snippets/objectToPairs.md: -------------------------------------------------------------------------------- 1 | ### objectToPairs 2 | 3 | Creates an array of key-value pair arrays from an object. 4 | 5 | Use `Object.keys()` and `Array.map()` to iterate over the object's keys and produce an array with key-value pairs. 6 | 7 | ```js 8 | const objectToPairs = obj => Object.keys(obj).map(k => [k, obj[k]]); 9 | ``` 10 | 11 | ```js 12 | objectToPairs({ a: 1, b: 2 }); // [['a',1],['b',2]] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/chunk.zh.md: -------------------------------------------------------------------------------- 1 | ### 块 2 | 3 | 将一个数组分块成指定大小的较小数组. 4 | 5 | 使用`array.from()`创建一个新的数组,适合将要生产的数据块`array.slice()`将新数组的每个元素映射到块的长度`尺寸`如果原始数组不能均匀分割,最后的块将包含剩余的元素. 6 | 7 | ```js 8 | const chunk = (arr, size) => 9 | Array.from({ length: Math.ceil(arr.length / size) }, (v, i) => 10 | arr.slice(i * size, i * size + size) 11 | ); 12 | ``` 13 | 14 | ```js 15 | chunk([1, 2, 3, 4, 5], 2); // [[1,2],[3,4],[5]] 16 | ``` -------------------------------------------------------------------------------- /snippets/countOccurrences.md: -------------------------------------------------------------------------------- 1 | ### countOccurrences 2 | 3 | Counts the occurrences of a value in an array. 4 | 5 | Use `Array.reduce()` to increment a counter each time you encounter the specific value inside the array. 6 | 7 | ```js 8 | const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a + 0), 0); 9 | ``` 10 | 11 | ```js 12 | countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/dropRight.md: -------------------------------------------------------------------------------- 1 | ### dropRight 2 | 3 | Returns a new array with `n` elements removed from the right. 4 | 5 | Use `Array.slice()` to slice the remove the specified number of elements from the right. 6 | 7 | ```js 8 | const dropRight = (arr, n = 1) => arr.slice(0, -n); 9 | ``` 10 | 11 | ```js 12 | dropRight([1, 2, 3]); // [1,2] 13 | dropRight([1, 2, 3], 2); // [1] 14 | dropRight([1, 2, 3], 42); // [] 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/median.zh.md: -------------------------------------------------------------------------------- 1 | ### 中位数 2 | 3 | 返回数字数组的中位数. 4 | 5 | 找到数组的中间,使用`中的Array.sort()`对数值进行排序. 如果返回中间数字`长度`是奇数,否则两个中间数的平均值. 6 | 7 | ```js 8 | const median = arr => { 9 | const mid = Math.floor(arr.length / 2), 10 | nums = [...arr].sort((a, b) => a - b); 11 | return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2; 12 | }; 13 | ``` 14 | 15 | ```js 16 | median([5, 6, 50, 1, -5]); // 5 17 | ``` -------------------------------------------------------------------------------- /snippets/serializeCookie.md: -------------------------------------------------------------------------------- 1 | ### serializeCookie 2 | 3 | Serialize a cookie name-value pair into a Set-Cookie header string. 4 | 5 | Use template literals and `encodeURIComponent()` to create the appropriate string. 6 | 7 | ```js 8 | const serializeCookie = (name, val) => `${encodeURIComponent(name)}=${encodeURIComponent(val)}`; 9 | ``` 10 | 11 | ```js 12 | serializeCookie('foo', 'bar'); // 'foo=bar' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/symmetricDifference.zh.md: -------------------------------------------------------------------------------- 1 | ### 对称差 2 | 3 | 返回两个数组之间的对称差异. 4 | 5 | 创建一个`组`从每个数组中,然后使用`array.filter()`在他们每个人只保留价值不包含在另一个. 6 | 7 | ```js 8 | const symmetricDifference = (a, b) => { 9 | const sA = new Set(a), 10 | sB = new Set(b); 11 | return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; 12 | }; 13 | ``` 14 | 15 | ```js 16 | symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4] 17 | ``` -------------------------------------------------------------------------------- /snippets/toggleClass.md: -------------------------------------------------------------------------------- 1 | ### toggleClass 2 | 3 | Toggle a class for an element. 4 | 5 | Use `element.classList.toggle()` to toggle the specified class for the element. 6 | 7 | ```js 8 | const toggleClass = (el, className) => el.classList.toggle(className); 9 | ``` 10 | 11 | ```js 12 | toggleClass(document.querySelector('p.special'), 'special'); // The paragraph will not have the 'special' class anymore 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/coalesceFactory.zh.md: -------------------------------------------------------------------------------- 1 | ### coalescefactory 2 | 3 | 返回一个自定义的合并函数,返回返回的第一个参数`真正`从提供的参数验证功能. 4 | 5 | 使用`array.find()`返回返回的第一个参数`真正`从提供的参数验证功能. 6 | 7 | ```js 8 | const coalesceFactory = valid => (...args) => args.find(valid); 9 | ``` 10 | 11 | ```js 12 | const customCoalesce = coalesceFactory(_ => ![null, undefined, '', NaN].includes(_)); 13 | customCoalesce(undefined, null, NaN, '', 'Waldo'); // "Waldo" 14 | ``` -------------------------------------------------------------------------------- /snippets/detectDeviceType.zh.md: -------------------------------------------------------------------------------- 1 | ### detectdevicetype 2 | 3 | 检测到网站在移动设备或台式机/笔记本电脑上打开. 4 | 5 | 使用正则表达式来测试`navigator.userAgent的`财产来确定设备是移动设备还是台式机/笔记本电脑. 6 | 7 | ```js 8 | const detectDeviceType = () => 9 | /AndroidƜwebOSƜiPhoneƜiPadƜiPodƜBlackBerryƜIEMobileƜOpera Mini/i.test(navigator.userAgent) 10 | ? 'Mobile' 11 | : 'Desktop'; 12 | ``` 13 | 14 | ```js 15 | detectDeviceType(); // "Mobile" or "Desktop" 16 | ``` -------------------------------------------------------------------------------- /snippets/intersection.md: -------------------------------------------------------------------------------- 1 | ### intersection 2 | 3 | Returns a list of elements that exist in both arrays. 4 | 5 | Create a `Set` from `b`, then use `Array.filter()` on `a` to only keep values contained in `b`. 6 | 7 | ```js 8 | const intersection = (a, b) => { 9 | const s = new Set(b); 10 | return a.filter(x => s.has(x)); 11 | }; 12 | ``` 13 | 14 | ```js 15 | intersection([1, 2, 3], [4, 3, 2]); // [2,3] 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets/lcm.zh.md: -------------------------------------------------------------------------------- 1 | ### LCM 2 | 3 | 返回两个或更多数字的最小公倍数. 4 | 5 | 使用最大公约数(gcd)公式和事实`lcm(x,y)= x * y / gcd(x,y)`确定最小公倍数. gcd公式使用递归. 6 | 7 | ```js 8 | const lcm = (...arr) => { 9 | const gcd = (x, y) => (!y ? x : gcd(y, x % y)); 10 | const _lcm = (x, y) => x * y / gcd(x, y); 11 | return [...arr].reduce((a, b) => _lcm(a, b)); 12 | }; 13 | ``` 14 | 15 | ```js 16 | lcm(12, 7); // 84 17 | lcm(...[1, 3, 4, 5]); // 60 18 | ``` -------------------------------------------------------------------------------- /snippets/powerset.md: -------------------------------------------------------------------------------- 1 | ### powerset 2 | 3 | Returns the powerset of a given array of numbers. 4 | 5 | Use `Array.reduce()` combined with `Array.map()` to iterate over elements and combine into an array containing all combinations. 6 | 7 | ```js 8 | const powerset = arr => arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]); 9 | ``` 10 | 11 | ```js 12 | powerset([1, 2]); // [[], [1], [2], [2,1]] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/sample.md: -------------------------------------------------------------------------------- 1 | ### sample 2 | 3 | Returns a random element from an array. 4 | 5 | Use `Math.random()` to generate a random number, multiply it by `length` and round it of to the nearest whole number using `Math.floor()`. 6 | This method also works with strings. 7 | 8 | ```js 9 | const sample = arr => arr[Math.floor(Math.random() * arr.length)]; 10 | ``` 11 | 12 | ```js 13 | sample([3, 7, 9, 11]); // 9 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/timeTaken.zh.md: -------------------------------------------------------------------------------- 1 | ### 所用的时间 2 | 3 | 度量一个函数执行的时间. 4 | 5 | 使用`console.time()`和`console.timeend()`来衡量开始和结束时间之间的差异,以确定回调执行多长时间. 6 | 7 | ```js 8 | const timeTaken = callback => { 9 | console.time('timeTaken'); 10 | const r = callback(); 11 | console.timeEnd('timeTaken'); 12 | return r; 13 | }; 14 | ``` 15 | 16 | ```js 17 | timeTaken(() => Math.pow(2, 10)); // 1024, (logged): timeTaken: 0.02099609375ms 18 | ``` -------------------------------------------------------------------------------- /snippets/untildify.md: -------------------------------------------------------------------------------- 1 | ### untildify 2 | 3 | Converts a tilde path to an absolute path. 4 | 5 | Use `String.replace()` with a regular expression and `OS.homedir()` to replace the `~` in the start of the path with the home directory. 6 | 7 | ```js 8 | const untildify = str => str.replace(/^~($|\/|\\)/, `${require('os').homedir()}$1`); 9 | ``` 10 | 11 | ```js 12 | untildify('~/node'); // '/Users/aUser/node' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/JSONToFile.zh.md: -------------------------------------------------------------------------------- 1 | ### jsontofile 2 | 3 | 写一个json对象到一个文件. 4 | 5 | 使用`fs.writefile()`,模板文字和`json.stringify()`写一个`JSON`反对`以.json`文件. 6 | 7 | ```js 8 | const fs = require('fs'); 9 | const JSONToFile = (obj, filename) => 10 | fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); 11 | ``` 12 | 13 | ```js 14 | JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json' 15 | ``` -------------------------------------------------------------------------------- /snippets/yesNo.zh.md: -------------------------------------------------------------------------------- 1 | ### YESNO 2 | 3 | 回报`真正`如果字符串是`ÿ`/`是`要么`假`如果字符串是`ñ`/`没有`. 4 | 5 | 使用`regexp.test()`检查字符串是否评估为`Y /是的`要么`N /无`. 第二个参数,`高清`将默认答案设置为`没有`. 6 | 7 | ```js 8 | const yesNo = (val, def = false) => 9 | /^(yƜyes)$/i.test(val) ? true : /^(nƜno)$/i.test(val) ? false : def; 10 | ``` 11 | 12 | ```js 13 | yesNo('Y'); // true 14 | yesNo('yes'); // true 15 | yesNo('No'); // false 16 | yesNo('Foo', true); // true 17 | ``` -------------------------------------------------------------------------------- /snippets/average.md: -------------------------------------------------------------------------------- 1 | ### average 2 | 3 | Returns the average of an of two or more numbers. 4 | 5 | Use `Array.reduce()` to add each value to an accumulator, initialized with a value of `0`, divide by the `length` of the array. 6 | 7 | ```js 8 | const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length; 9 | ``` 10 | 11 | ```js 12 | average(...[1, 2, 3]); // 2 13 | average(1, 2, 3); // 2 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/randomIntegerInRange.md: -------------------------------------------------------------------------------- 1 | ### randomIntegerInRange 2 | 3 | Returns a random integer in the specified range. 4 | 5 | Use `Math.random()` to generate a random number and map it to the desired range, using `Math.floor()` to make it an integer. 6 | 7 | ```js 8 | const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min; 9 | ``` 10 | 11 | ```js 12 | randomIntegerInRange(0, 5); // 2 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/round.md: -------------------------------------------------------------------------------- 1 | ### round 2 | 3 | Rounds a number to a specified amount of digits. 4 | 5 | Use `Math.round()` and template literals to round the number to the specified number of digits. 6 | Omit the second argument, `decimals` to round to an integer. 7 | 8 | ```js 9 | const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`); 10 | ``` 11 | 12 | ```js 13 | round(1.005, 2); // 1.01 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/curry.zh.md: -------------------------------------------------------------------------------- 1 | ### 咖喱 2 | 3 | 咖喱功能. 4 | 5 | 使用递归. 如果提供的参数数量(`ARGS`)就足够了,调用传递函数`FN`. 另外,返回一个curried函数`FN`如果你想要一个接受可变数目参数的函数(一个可变参数函数,例如,`math.min()`),您可以选择将参数个数传递给第二个参数`元数`. 6 | 7 | ```js 8 | const curry = (fn, arity = fn.length, ...args) => 9 | arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args); 10 | ``` 11 | 12 | ```js 13 | curry(Math.pow)(2)(10); // 1024 14 | curry(Math.min, 3)(10)(50)(2); // 2 15 | ``` -------------------------------------------------------------------------------- /snippets/isObject.zh.md: -------------------------------------------------------------------------------- 1 | ### 则IsObject 2 | 3 | 返回一个布尔值,确定传递的值是否是一个对象. 4 | 5 | 使用`目的`构造函数为给定的值创建一个对象包装器. `如果价值是`空值`要么`未定义,创建并返回一个空的对象. 否则,返回对应于给定值的类型的对象. 6 | 7 | ```js 8 | const isObject = obj => obj === Object(obj); 9 | ``` 10 | 11 | ```js 12 | isObject([1, 2, 3, 4]); // true 13 | isObject([]); // true 14 | isObject(['Hello!']); // true 15 | isObject({ a: 1 }); // true 16 | isObject({}); // true 17 | isObject(true); // false 18 | ``` -------------------------------------------------------------------------------- /snippets/mapKeys.zh.md: -------------------------------------------------------------------------------- 1 | ### 映射键 2 | 3 | 通过为每个键运行提供的功能和与提供的对象相同的值来创建具有键生成的对象. 4 | 5 | 使用`object.keys(OBJ)`遍历对象的keys.use`array.reduce()`使用相同的值和映射的键创建一个新的对象`FN`. 6 | 7 | ```js 8 | const mapKeys = (obj, fn) => 9 | Object.keys(obj).reduce((acc, k) => { 10 | acc[fn(obj[k], k, obj)] = obj[k]; 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | mapKeys({ a: 1, b: 2 }, (val, key) => key + val); // { a1: 1, b2: 2 } 17 | ``` -------------------------------------------------------------------------------- /snippets/sdbm.zh.md: -------------------------------------------------------------------------------- 1 | ### SBDM 2 | 3 | 将输入字符串散列为整数. 4 | 5 | 使用`string.split( '')`和`array.reduce()`创建输入字符串的散列,利用位移. 6 | 7 | ```js 8 | const sdbm = str => { 9 | let arr = str.split(''); 10 | return arr.reduce( 11 | (hashCode, currentVal) => 12 | (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), 13 | 0 14 | ); 15 | }; 16 | ``` 17 | 18 | ```js 19 | sdbm('name'); // -3521204949 20 | ``` -------------------------------------------------------------------------------- /snippets/capitalizeEveryWord.md: -------------------------------------------------------------------------------- 1 | ### capitalizeEveryWord 2 | 3 | Capitalizes the first letter of every word in a string. 4 | 5 | Use `String.replace()` to match the first character of each word and `String.toUpperCase()` to capitalize it. 6 | 7 | ```js 8 | const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase()); 9 | ``` 10 | 11 | ```js 12 | capitalizeEveryWord('hello world!'); // 'Hello World!' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/collectInto.zh.md: -------------------------------------------------------------------------------- 1 | ### collectinto 2 | 3 | 将接受数组的函数改为可变函数. 4 | 5 | 给定一个函数,返回一个闭包,将所有输入收集到一个数组接受函数中. 6 | 7 | ```js 8 | const collectInto = fn => (...args) => fn(args); 9 | ``` 10 | 11 | ```js 12 | const Pall = collectInto(Promise.all.bind(Promise)); 13 | let p1 = Promise.resolve(1); 14 | let p2 = Promise.resolve(2); 15 | let p3 = new Promise(resolve => setTimeout(resolve, 2000, 3)); 16 | Pall(p1, p2, p3).then(console.log); 17 | ``` -------------------------------------------------------------------------------- /snippets/flip.zh.md: -------------------------------------------------------------------------------- 1 | ### 翻动 2 | 3 | flip将函数作为参数,然后将第一个参数作为最后一个参数. 4 | 5 | 返回一个包含可变参数的闭包,然后拼接最后一个参数,使其成为第一个参数,然后应用其余参数. 6 | 7 | ```js 8 | const flip = fn => (...args) => fn(args.pop(), ...args); 9 | ``` 10 | 11 | ```js 12 | let a = { name: 'John Smith' }; 13 | let b = {}; 14 | const mergeFrom = flip(Object.assign); 15 | let mergePerson = mergeFrom.bind(null, a); 16 | mergePerson(b); // == b 17 | b = {}; 18 | Object.assign(b, a); // == b 19 | ``` -------------------------------------------------------------------------------- /snippets/getDaysDiffBetweenDates.md: -------------------------------------------------------------------------------- 1 | ### getDaysDiffBetweenDates 2 | 3 | Returns the difference (in days) between two dates. 4 | 5 | Calculate the difference (in days) between two `Date` objects. 6 | 7 | ```js 8 | const getDaysDiffBetweenDates = (dateInitial, dateFinal) => 9 | (dateFinal - dateInitial) / (1000 * 3600 * 24); 10 | ``` 11 | 12 | ```js 13 | getDaysDiffBetweenDates(new Date('2017-12-13'), new Date('2017-12-22')); // 9 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/indexOfAll.zh.md: -------------------------------------------------------------------------------- 1 | ### indexofall 2 | 3 | 返回所有的索引`VAL`在一个数组中. `如果`VAL`从不发生,返回`\[] 4 | 5 | . `使用`array.foreach()`循环元素和`的Array.push()存储匹配元素的索引. 返回索引数组. 6 | 7 | ```js 8 | const indexOfAll = (arr, val) => { 9 | const indices = []; 10 | arr.forEach((el, i) => el === val && indices.push(i)); 11 | return indices; 12 | }; 13 | ``` 14 | 15 | ```js 16 | indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3] 17 | indexOfAll([1, 2, 3], 4); // [] 18 | ``` -------------------------------------------------------------------------------- /snippets/setStyle.md: -------------------------------------------------------------------------------- 1 | ### setStyle 2 | 3 | Sets the value of a CSS rule for the specified element. 4 | 5 | Use `element.style` to set the value of the CSS rule for the specified element to `val`. 6 | 7 | ```js 8 | const setStyle = (el, ruleName, val) => (el.style[ruleName] = val); 9 | ``` 10 | 11 | ```js 12 | setStyle(document.querySelector('p'), 'font-size', '20px'); // The first

    element on the page will have a font-size of 20px 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/words.zh.md: -------------------------------------------------------------------------------- 1 | ### 话 2 | 3 | 将给定的字符串转换为单词数组. 4 | 5 | 使用`string.split()`与提供的模式(默认为非alpha作为正则表达式)转换为字符串数组. `使用`array.filter()删除任何空的strings.omit第二个参数使用默认的正则表达式. 6 | 7 | ```js 8 | const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean); 9 | ``` 10 | 11 | ```js 12 | words('I love javaScript!!'); // ["I", "love", "javaScript"] 13 | words('python, javaScript & coffee'); // ["python", "javaScript", "coffee"] 14 | ``` -------------------------------------------------------------------------------- /snippets_archive/removeVowels.md: -------------------------------------------------------------------------------- 1 | ### removeVowels 2 | 3 | Returns all the vowels in a `str` replaced by `repl`. 4 | 5 | Use `String.replace()` with a regexp to replace all vowels in `str`. 6 | Omot `repl` to use a default value of `''`. 7 | 8 | ```js 9 | const removeVowels = (str, repl = '') => str.replace(/[aeiou]/gi,repl); 10 | ``` 11 | 12 | ```js 13 | removeVowels("foobAr"); // "fbr" 14 | removeVowels("foobAr","*"); // "f**b*r" 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/chainAsync.zh.md: -------------------------------------------------------------------------------- 1 | ### chainasync 2 | 3 | 链异步功能. 4 | 5 | 循环遍历包含异步事件的函数数组,调用`下一个`当每个异步事件已经完成时. 6 | 7 | ```js 8 | const chainAsync = fns => { 9 | let curr = 0; 10 | const next = () => fns[curr++](next); 11 | next(); 12 | }; 13 | ``` 14 | 15 | ```js 16 | chainAsync([ 17 | next => { 18 | console.log('0 seconds'); 19 | setTimeout(next, 1000); 20 | }, 21 | next => { 22 | console.log('1 second'); 23 | } 24 | ]); 25 | ``` -------------------------------------------------------------------------------- /snippets/isArrayLike.zh.md: -------------------------------------------------------------------------------- 1 | ### isarraylike 2 | 3 | 检查提供的参数是否类似于数组(即可迭代). 4 | 5 | 使用扩展运算符(`...`)来检查提供的参数是否可迭代`试着抓`块和逗号运算符(`,`)返回适当的值. 6 | 7 | ```js 8 | const isArrayLike = val => { 9 | try { 10 | return [...val], true; 11 | } catch (e) { 12 | return false; 13 | } 14 | }; 15 | ``` 16 | 17 | ```js 18 | isArrayLike(document.querySelectorAll('.className')); // true 19 | isArrayLike('abc'); // true 20 | isArrayLike(null); // false 21 | ``` -------------------------------------------------------------------------------- /snippets/pipeFunctions.zh.md: -------------------------------------------------------------------------------- 1 | ### pipefunctions 2 | 3 | 执行从左到右的功能组合. 4 | 5 | 使用`array.reduce()`与传播运算符(`...`)执行从左到右的函数组合. 第一个(最左边的)函数可以接受一个或多个参数;其余的功能必须是一元的. 6 | 7 | ```js 8 | const pipeFunctions = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args))); 9 | ``` 10 | 11 | ```js 12 | const add5 = x => x + 5; 13 | const multiply = (x, y) => x * y; 14 | const multiplyAndAdd5 = pipeFunctions(multiply, add5); 15 | multiplyAndAdd5(5, 2); // 15 16 | ``` -------------------------------------------------------------------------------- /snippets/randomHexColorCode.zh.md: -------------------------------------------------------------------------------- 1 | ### randomhexcolorcode 2 | 3 | 生成一个随机的十六进制颜色代码. 4 | 5 | 使用`的Math.random`生成一个随机的24位(6x4bits)十六进制数字. `使用位移,然后将其转换为十六进制字符串使用`的ToString(16). 6 | 7 | ```js 8 | const randomHexColorCode = () => { 9 | let n = ((Math.random() * 0xfffff) Ɯ 0).toString(16); 10 | return '#' + (n.length !== 6 ? ((Math.random() * 0xf) Ɯ 0).toString(16) + n : n); 11 | }; 12 | ``` 13 | 14 | ```js 15 | randomHexColorCode(); // "#e34155" 16 | ``` -------------------------------------------------------------------------------- /snippets/clampNumber.md: -------------------------------------------------------------------------------- 1 | ### clampNumber 2 | 3 | Clamps `num` within the inclusive range specified by the boundary values `a` and `b`. 4 | 5 | If `num` falls within the range, return `num`. 6 | Otherwise, return the nearest number in the range. 7 | 8 | ```js 9 | const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b)); 10 | ``` 11 | 12 | ```js 13 | clampNumber(2, 3, 5); // 3 14 | clampNumber(1, -1, -5); // -1 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/off.zh.md: -------------------------------------------------------------------------------- 1 | ### 离 2 | 3 | 从元素中移除一个事件监听器. 4 | 5 | 使用`eventtarget.removeeventlistener()`从元素中删除事件侦听器. `省略第四个参数`OPTS`使用`假或者根据添加事件侦听器时使用的选项来指定它. 6 | 7 | ```js 8 | const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); 9 | ``` 10 | 11 | ```js 12 | const fn = () => console.log('!'); 13 | document.body.addEventListener('click', fn); 14 | off(document.body, 'click', fn); // no longer logs '!' upon clicking on the page 15 | ``` -------------------------------------------------------------------------------- /snippets/tomorrow.md: -------------------------------------------------------------------------------- 1 | ### tomorrow 2 | 3 | Results in a string representation of tomorrow's date. 4 | Use `new Date()` to get today's date, adding `86400000` of seconds to it(24 hours), using `Date.toISOString()` to convert Date object to string. 5 | 6 | ```js 7 | const tomorrow = () => new Date(new Date().getTime() + 86400000).toISOString().split('T')[0]; 8 | ``` 9 | 10 | ```js 11 | tomorrow(); // 2017-12-27 (if current date is 2017-12-26) 12 | ``` 13 | -------------------------------------------------------------------------------- /snippets/zipObject.zh.md: -------------------------------------------------------------------------------- 1 | ### zipobject 2 | 3 | 给定一个有效的属性标识符和一个数组值的数组,返回一个将属性关联到值的对象. 4 | 5 | 因为一个对象可以有未定义的值,但是没有未定义的属性指针,所以这个属性数组用来决定使用结果对象的结构`array.reduce()`. 6 | 7 | ```js 8 | const zipObject = (props, values) => 9 | props.reduce((obj, prop, index) => ((obj[prop] = values[index]), obj), {}); 10 | ``` 11 | 12 | ```js 13 | zipObject(['a', 'b', 'c'], [1, 2]); // {a: 1, b: 2, c: undefined} 14 | zipObject(['a', 'b'], [1, 2, 3]); // {a: 1, b: 2} 15 | ``` -------------------------------------------------------------------------------- /snippets/deepFlatten.md: -------------------------------------------------------------------------------- 1 | ### deepFlatten 2 | 3 | Deep flattens an array. 4 | 5 | Use recursion. 6 | Use `Array.concat()` with an empty array (`[]`) and the spread operator (`...`) to flatten an array. 7 | Recursively flatten each element that is an array. 8 | 9 | ```js 10 | const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v))); 11 | ``` 12 | 13 | ```js 14 | deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5] 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/getScrollPosition.zh.md: -------------------------------------------------------------------------------- 1 | ### 调用getScrollPosition 2 | 3 | 返回当前页面的滚动位置. 4 | 5 | 使用`pagexoffset`和`pageyoffset`如果他们被定义,否则`scrollleft`和`scrollTop的`你可以省略`埃尔`使用默认值`窗口`. 6 | 7 | ```js 8 | const getScrollPosition = (el = window) => ({ 9 | x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, 10 | y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop 11 | }); 12 | ``` 13 | 14 | ```js 15 | getScrollPosition(); // {x: 0, y: 200} 16 | ``` -------------------------------------------------------------------------------- /snippets/isAbsoluteURL.md: -------------------------------------------------------------------------------- 1 | ### isAbsoluteURL 2 | 3 | Returns `true` if the given string is an absolute URL, `false` otherwise. 4 | 5 | Use a regular expression to test if the string is an absolute URL. 6 | 7 | ```js 8 | const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str); 9 | ``` 10 | 11 | ```js 12 | isAbsoluteURL('https://google.com'); // true 13 | isAbsoluteURL('ftp://www.myserver.net'); // true 14 | isAbsoluteURL('/foo/bar'); // false 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/sumBy.zh.md: -------------------------------------------------------------------------------- 1 | ### sumby 2 | 3 | 在使用提供的函数将每个元素映射到一个值之后,返回一个数组的总和. 4 | 5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`. 6 | 7 | ```js 8 | const sumBy = (arr, fn) => 9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0); 10 | ``` 11 | 12 | ```js 13 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 20 14 | sumBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 20 15 | ``` -------------------------------------------------------------------------------- /snippets_archive/JSONToDate.md: -------------------------------------------------------------------------------- 1 | ### JSONToDate 2 | 3 | Converts a JSON object to a date. 4 | 5 | Use `Date()`, to convert dates in JSON format to readable format (`dd/mm/yyyy`). 6 | 7 | ```js 8 | const JSONToDate = arr => { 9 | const dt = new Date(parseInt(arr.toString().substr(6))); 10 | return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`; 11 | }; 12 | ``` 13 | 14 | ```js 15 | JSONToDate(/Date(1489525200000)/); // "14/3/2017" 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets_archive/isArmstrongNumber.zh.md: -------------------------------------------------------------------------------- 1 | ### isarmstrongnumber 2 | 3 | 检查给定的号码是否是阿姆斯特朗号码. 4 | 5 | 将给定的数字转换为数字数组. `使用指数运算符(`\*\*`)为每个数字获得适当的权力并总结出来. `如果总和等于数字本身,则返回`真正`除此以外假. 6 | 7 | ```js 8 | const isArmstrongNumber = digits => 9 | (arr => arr.reduce((a, d) => a + parseInt(d) ** arr.length, 0) == digits)( 10 | (digits + '').split('') 11 | ); 12 | ``` 13 | 14 | ```js 15 | isArmstrongNumber(1634); // true 16 | isArmstrongNumber(56); // false 17 | ``` -------------------------------------------------------------------------------- /snippets/RGBToHex.md: -------------------------------------------------------------------------------- 1 | ### RGBToHex 2 | 3 | Converts the values of RGB components to a color code. 4 | 5 | Convert given RGB parameters to hexadecimal string using bitwise left-shift operator (`<<`) and `toString(16)`, then `String.padStart(6,'0')` to get a 6-digit hexadecimal value. 6 | 7 | ```js 8 | const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0'); 9 | ``` 10 | 11 | ```js 12 | RGBToHex(255, 165, 1); // 'ffa501' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/call.zh.md: -------------------------------------------------------------------------------- 1 | ### 呼叫 2 | 3 | 给定一个关键和一组参数,给定一个上下文时调用它们. 4 | 5 | 主要用于构图. 使用闭包来调用存储的参数的存储键. 6 | 7 | ```js 8 | const call = (key, ...args) => context => context[key](...args); 9 | ``` 10 | 11 | ```js 12 | Promise.resolve([1, 2, 3]) 13 | .then(call('map', x => 2 * x)) 14 | .then(console.log); //[ 2, 4, 6 ] 15 | const map = call.bind(null, 'map'); 16 | Promise.resolve([1, 2, 3]) 17 | .then(map(x => 2 * x)) 18 | .then(console.log); //[ 2, 4, 6 ] 19 | ``` -------------------------------------------------------------------------------- /snippets/isValidJSON.zh.md: -------------------------------------------------------------------------------- 1 | ### isvalidjson 2 | 3 | 检查提供的参数是否是有效的json. 4 | 5 | 使用`JSON.parse()来`和a`试着抓`块来检查提供的参数是否是有效的json. 6 | 7 | ```js 8 | const isValidJSON = obj => { 9 | try { 10 | JSON.parse(obj); 11 | return true; 12 | } catch (e) { 13 | return false; 14 | } 15 | }; 16 | ``` 17 | 18 | ```js 19 | isValidJSON('{"name":"Adam","age":20}'); // true 20 | isValidJSON('{"name":"Adam",age:"20"}'); // false 21 | isValidJSON(null); // true 22 | ``` -------------------------------------------------------------------------------- /snippets/randomIntArrayInRange.zh.md: -------------------------------------------------------------------------------- 1 | ### randomintarrayinrange 2 | 3 | 返回指定范围内的n个随机整数的数组. 4 | 5 | 使用`array.from()`创建一个特定长度的空数组,`的Math.random()`生成一个随机数并将其映射到期望的范围,使用`math.floor()`使其成为一个整数. 6 | 7 | ```js 8 | const randomIntArrayInRange = (min, max, n = 1) => 9 | Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min); 10 | ``` 11 | 12 | ```js 13 | randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ] 14 | ``` -------------------------------------------------------------------------------- /snippets/without.md: -------------------------------------------------------------------------------- 1 | ### without 2 | 3 | Filters out the elements of an array, that have one of the specified values. 4 | 5 | Use `Array.filter()` to create an array excluding(using `!Array.includes()`) all given values. 6 | 7 | _(For a snippet that mutates the original array see [`pull`](#pull))_ 8 | 9 | ```js 10 | const without = (arr, ...args) => arr.filter(v => !args.includes(v)); 11 | ``` 12 | 13 | ```js 14 | without([2, 1, 2, 3], 1, 2); // [3] 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/capitalize.zh.md: -------------------------------------------------------------------------------- 1 | ### 利用 2 | 3 | 大写字符串的第一个字母. 4 | 5 | 使用数组解构和`string.touppercase()`首字母大写,`...休息`在第一个字母后再获取字符数组`array.join( '')`使它再次成为一个字符串`lowerrest`参数保持字符串的其余部分不变,或者将其设置为`真正`转换为小写. 6 | 7 | ```js 8 | const capitalize = ([first, ...rest], lowerRest = false) => 9 | first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join('')); 10 | ``` 11 | 12 | ```js 13 | capitalize('fooBar'); // 'FooBar' 14 | capitalize('fooBar', true); // 'Foobar' 15 | ``` -------------------------------------------------------------------------------- /snippets/redirect.md: -------------------------------------------------------------------------------- 1 | ### redirect 2 | 3 | Redirects to a specified URL. 4 | 5 | Use `window.location.href` or `window.location.replace()` to redirect to `url`. 6 | Pass a second argument to simulate a link click (`true` - default) or an HTTP redirect (`false`). 7 | 8 | ```js 9 | const redirect = (url, asLink = true) => 10 | asLink ? (window.location.href = url) : window.location.replace(url); 11 | ``` 12 | 13 | ```js 14 | redirect('https://google.com'); 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/sortCharactersInString.md: -------------------------------------------------------------------------------- 1 | ### sortCharactersInString 2 | 3 | Alphabetically sorts the characters in a string. 4 | 5 | Use the spread operator (`...`), `Array.sort()` and `String.localeCompare()` to sort the characters in `str`, recombine using `String.join('')`. 6 | 7 | ```js 8 | const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join(''); 9 | ``` 10 | 11 | ```js 12 | sortCharactersInString('cabbage'); // 'aabbceg' 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/spreadOver.md: -------------------------------------------------------------------------------- 1 | ### spreadOver 2 | 3 | Takes a variadic function and returns a closure that accepts an array of arguments to map to the inputs of the function. 4 | 5 | Use closures and the spread operator (`...`) to map the array of arguments to the inputs of the function. 6 | 7 | ```js 8 | const spreadOver = fn => argsArr => fn(...argsArr); 9 | ``` 10 | 11 | ```js 12 | const arrayMax = spreadOver(Math.max); 13 | arrayMax([1, 2, 3]); // 3 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/toSafeInteger.md: -------------------------------------------------------------------------------- 1 | ### toSafeInteger 2 | 3 | Converts a value to a safe integer. 4 | 5 | Use `Math.max()` and `Math.min()` to find the closest safe value. 6 | Use `Math.round()` to convert to an integer. 7 | 8 | ```js 9 | const toSafeInteger = num => 10 | Math.round(Math.max(Math.min(num, Number.MAX_SAFE_INTEGER), Number.MIN_SAFE_INTEGER)); 11 | ``` 12 | 13 | ```js 14 | toSafeInteger('3.2'); // 3 15 | toSafeInteger(Infinity); // 9007199254740991 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets_archive/fibonacciCountUntilNum.md: -------------------------------------------------------------------------------- 1 | ### fibonacciCountUntilNum 2 | 3 | Returns the number of fibonnacci numbers up to `num`(`0` and `num` inclusive). 4 | 5 | Use a mathematical formula to calculate the number of fibonacci numbers until `num`. 6 | 7 | ```js 8 | const fibonacciCountUntilNum = num => 9 | Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2)); 10 | ``` 11 | 12 | ```js 13 | fibonacciCountUntilNum(10); // 7 14 | ``` 15 | -------------------------------------------------------------------------------- /test/createEventHub/createEventHub.js: -------------------------------------------------------------------------------- 1 | module.exports = createEventHub = () => ({ 2 | hub: Object.create(null), 3 | emit(event, data) { 4 | (this.hub[event] || []).forEach(handler => handler(data)); 5 | }, 6 | on(event, handler) { 7 | if (!this.hub[event]) this.hub[event] = []; 8 | this.hub[event].push(handler); 9 | }, 10 | off(event, handler) { 11 | const i = (this.hub[event] || []).findIndex(h => h === handler); 12 | if (i > -1) this.hub[event].splice(i, 1); 13 | } 14 | }); -------------------------------------------------------------------------------- /test/runAsync/runAsync.js: -------------------------------------------------------------------------------- 1 | module.exports = runAsync = fn => { 2 | const blob = `var fn = ${fn.toString()}; postMessage(fn());`; 3 | const worker = new Worker( 4 | URL.createObjectURL(new Blob([blob]), { 5 | type: 'application/javascript; charset=utf-8' 6 | }) 7 | ); 8 | return new Promise((res, rej) => { 9 | worker.onmessage = ({ data }) => { 10 | res(data), worker.terminate(); 11 | }; 12 | worker.onerror = err => { 13 | rej(err), worker.terminate(); 14 | }; 15 | }); 16 | }; -------------------------------------------------------------------------------- /snippets/initializeArrayWithValues.md: -------------------------------------------------------------------------------- 1 | ### initializeArrayWithValues 2 | 3 | Initializes and fills an array with the specified values. 4 | 5 | Use `Array(n)` to create an array of the desired length, `fill(v)` to fill it with the desired values. 6 | You can omit `val` to use a default value of `0`. 7 | 8 | ```js 9 | const initializeArrayWithValues = (n, val = 0) => Array(n).fill(val); 10 | ``` 11 | 12 | ```js 13 | initializeArrayWithValues(5, 2); // [2,2,2,2,2] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/runPromisesInSeries.zh.md: -------------------------------------------------------------------------------- 1 | ### runpromisesinseries 2 | 3 | 运行一连串的承诺. 4 | 5 | 使用`array.reduce()`创建一个承诺链,每个承诺在解决时都会返回下一个承诺. 6 | 7 | ```js 8 | const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve()); 9 | ``` 10 | 11 | ```js 12 | const delay = d => new Promise(r => setTimeout(r, d)); 13 | runPromisesInSeries([() => delay(1000), () => delay(2000)]); // Executes each promise sequentially, taking a total of 3 seconds to complete 14 | ``` -------------------------------------------------------------------------------- /snippets/transform.zh.md: -------------------------------------------------------------------------------- 1 | ### 转变 2 | 3 | 对累加器和对象中的每个键(从左到右)应用一个函数. 4 | 5 | 使用`object.keys(OBJ)`遍历对象中的每个键,`array.reduce()`调用对指定的累加器应用指定的函数. 6 | 7 | ```js 8 | const transform = (obj, fn, acc) => Object.keys(obj).reduce((a, k) => fn(a, obj[k], k, obj), acc); 9 | ``` 10 | 11 | ```js 12 | transform( 13 | { a: 1, b: 2, c: 1 }, 14 | (r, v, k) => { 15 | (r[v] ƜƜ (r[v] = [])).push(k); 16 | return r; 17 | }, 18 | {} 19 | ); // { '1': ['a', 'c'], '2': ['b'] } 20 | ``` -------------------------------------------------------------------------------- /snippets/sleep.md: -------------------------------------------------------------------------------- 1 | ### sleep 2 | 3 | Delays the execution of an asynchronous function. 4 | 5 | Delay executing part of an `async` function, by putting it to sleep, returning a `Promise`. 6 | 7 | ```js 8 | const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); 9 | ``` 10 | 11 | ```js 12 | async function sleepyWork() { 13 | console.log("I'm going to sleep for 1 second."); 14 | await sleep(1000); 15 | console.log('I woke up after 1 second.'); 16 | } 17 | ``` 18 | -------------------------------------------------------------------------------- /test/on/on.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const on = require('./on.js'); 3 | 4 | test('Testing on', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof on === 'function', 'on is a Function'); 8 | //t.deepEqual(on(args..), 'Expected'); 9 | //t.equal(on(args..), 'Expected'); 10 | //t.false(on(args..), 'Expected'); 11 | //t.throws(on(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/JSONToFile.md: -------------------------------------------------------------------------------- 1 | ### JSONToFile 2 | 3 | Writes a JSON object to a file. 4 | 5 | Use `fs.writeFile()`, template literals and `JSON.stringify()` to write a `json` object to a `.json` file. 6 | 7 | ```js 8 | const fs = require('fs'); 9 | const JSONToFile = (obj, filename) => 10 | fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2)); 11 | ``` 12 | 13 | ```js 14 | JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json' 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/arrayToHtmlList.md: -------------------------------------------------------------------------------- 1 | ### arrayToHtmlList 2 | 3 | Converts the given array elements into `

  • ` tags and appends them to the list of the given id. 4 | 5 | Use `Array.map()` and `document.querySelector()` to create a list of html tags. 6 | 7 | ```js 8 | const arrayToHtmlList = (arr, listID) => 9 | arr.map(item => (document.querySelector('#' + listID).innerHTML += `
  • ${item}
  • `)); 10 | ``` 11 | 12 | ```js 13 | arrayToHtmlList(['item 1', 'item 2'], 'myListID'); 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/inRange.zh.md: -------------------------------------------------------------------------------- 1 | ### 在范围内 2 | 3 | 检查给定的数字是否落在给定范围内. 4 | 5 | 使用算术比较来检查给定的数字是否在指定的范围内. 如果第二个参数,`结束`,没有指定,范围被认为是从`0`至`开始`. 6 | 7 | ```js 8 | const inRange = (n, start, end = null) => { 9 | if (end && start > end) end = [start, (start = end)][0]; 10 | return end == null ? n >= 0 && n < start : n >= start && n < end; 11 | }; 12 | ``` 13 | 14 | ```js 15 | inRange(3, 2, 5); // true 16 | inRange(3, 4); // true 17 | inRange(2, 3, 5); // false 18 | inrange(3, 2); // false 19 | ``` -------------------------------------------------------------------------------- /test/formatDuration/formatDuration.js: -------------------------------------------------------------------------------- 1 | module.exports = formatDuration = ms => { 2 | if (ms < 0) ms = -ms; 3 | const time = { 4 | day: Math.floor(ms / 86400000), 5 | hour: Math.floor(ms / 3600000) % 24, 6 | minute: Math.floor(ms / 60000) % 60, 7 | second: Math.floor(ms / 1000) % 60, 8 | millisecond: Math.floor(ms) % 1000 9 | }; 10 | return Object.entries(time) 11 | .filter(val => val[1] !== 0) 12 | .map(val => val[1] + ' ' + (val[1] !== 1 ? val[0] + 's' : val[0])) 13 | .join(', '); 14 | }; -------------------------------------------------------------------------------- /snippets/UUIDGeneratorBrowser.zh.md: -------------------------------------------------------------------------------- 1 | ### uuidgeneratorbrowser 2 | 3 | 在浏览器中生成一个uuid. 4 | 5 | 使用`加密`API生成一个UUID,符合[rfc4122](https://www.ietf.org/rfc/rfc4122.txt)版本4. 6 | 7 | ```js 8 | const UUIDGeneratorBrowser = () => 9 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 10 | (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) 11 | ); 12 | ``` 13 | 14 | ```js 15 | UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d' 16 | ``` -------------------------------------------------------------------------------- /snippets/decapitalize.zh.md: -------------------------------------------------------------------------------- 1 | ### decapitalize 2 | 3 | 将字符串的第一个字母去除. 4 | 5 | 使用数组解构和`string.tolowercase()`给首字母去封顶,`...休息`在第一个字母后再获取字符数组`array.join( '')`使它再次成为一个字符串`upperrest`参数保持字符串的其余部分不变,或者将其设置为`真正`转换为大写. 6 | 7 | ```js 8 | const decapitalize = ([first, ...rest], upperRest = false) => 9 | first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join('')); 10 | ``` 11 | 12 | ```js 13 | decapitalize('FooBar'); // 'fooBar' 14 | decapitalize('FooBar', true); // 'fOOBAR' 15 | ``` -------------------------------------------------------------------------------- /snippets/invertKeyValues.md: -------------------------------------------------------------------------------- 1 | ### invertKeyValues 2 | 3 | Inverts the key-value pairs of an object, without mutating it. 4 | 5 | Use `Object.keys()` and `Array.reduce()` to invert the key-value pairs of an object. 6 | 7 | ```js 8 | const invertKeyValues = obj => 9 | Object.keys(obj).reduce((acc, key) => { 10 | acc[obj[key]] = key; 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | invertKeyValues({ name: 'John', age: 20 }); // { 20: 'age', John: 'name' } 17 | ``` 18 | -------------------------------------------------------------------------------- /snippets/pick.md: -------------------------------------------------------------------------------- 1 | ### pick 2 | 3 | Picks the key-value pairs corresponding to the given keys from an object. 4 | 5 | Use `Array.reduce()` to convert the filtered/picked keys back to an object with the corresponding key-value pair if the key exists in the obj. 6 | 7 | ```js 8 | const pick = (obj, arr) => 9 | arr.reduce((acc, curr) => (curr in obj && (acc[curr] = obj[curr]), acc), {}); 10 | ``` 11 | 12 | ```js 13 | pick({ a: 1, b: '2', c: 3 }, ['a', 'c']); // { 'a': 1, 'c': 3 } 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/remove.zh.md: -------------------------------------------------------------------------------- 1 | ### 去掉 2 | 3 | 从给定函数返回的数组中移除元素`假`. 4 | 5 | 使用`array.filter()`找到返回真值的数组元素`array.reduce()`使用删除元素`方法Array.splice()`.the`FUNC`被调用三个参数(`值,索引,数组`). 6 | 7 | ```js 8 | const remove = (arr, func) => 9 | Array.isArray(arr) 10 | ? arr.filter(func).reduce((acc, val) => { 11 | arr.splice(arr.indexOf(val), 1); 12 | return acc.concat(val); 13 | }, []) 14 | : []; 15 | ``` 16 | 17 | ```js 18 | remove([1, 2, 3, 4], n => n % 2 == 0); // [2, 4] 19 | ``` -------------------------------------------------------------------------------- /snippets/shuffle.zh.md: -------------------------------------------------------------------------------- 1 | ### 拖曳 2 | 3 | 随机化一个数组的值的顺序,返回一个新的数组. 4 | 5 | 使用[fisher-yates算法](https://github.com/chalarangelo/30-seconds-of-code#shuffle)重新排列数组的元素. 6 | 7 | ```js 8 | const shuffle = ([...arr]) => { 9 | let m = arr.length; 10 | while (m) { 11 | const i = Math.floor(Math.random() * m--); 12 | [arr[m], arr[i]] = [arr[i], arr[m]]; 13 | } 14 | return arr; 15 | }; 16 | ``` 17 | 18 | ```js 19 | const foo = [1, 2, 3]; 20 | shuffle(foo); // [2,3,1], foo = [1,2,3] 21 | ``` -------------------------------------------------------------------------------- /snippets/sortedIndex.zh.md: -------------------------------------------------------------------------------- 1 | ### sortedindex 2 | 3 | 返回值应该插入到数组中的最低索引,以保持其排序顺序. 4 | 5 | 检查数组是否按降序(松散地)排序`array.findindex()`找到元素应该被插入的适当的索引. 6 | 7 | ```js 8 | const sortedIndex = (arr, n) => { 9 | const isDescending = arr[0] > arr[arr.length - 1]; 10 | const index = arr.findIndex(el => (isDescending ? n >= el : n <= el)); 11 | return index === -1 ? arr.length : index; 12 | }; 13 | ``` 14 | 15 | ```js 16 | sortedIndex([5, 3, 2, 1], 4); // 1 17 | sortedIndex([30, 50], 40); // 1 18 | ``` -------------------------------------------------------------------------------- /test/off/off.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const off = require('./off.js'); 3 | 4 | test('Testing off', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof off === 'function', 'off is a Function'); 8 | //t.deepEqual(off(args..), 'Expected'); 9 | //t.equal(off(args..), 'Expected'); 10 | //t.false(off(args..), 'Expected'); 11 | //t.throws(off(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/UUIDGeneratorNode.zh.md: -------------------------------------------------------------------------------- 1 | ### uuidgeneratornode 2 | 3 | 在node.js中生成一个uuid 4 | 5 | 使用`加密`API生成一个UUID,符合[rfc4122](https://www.ietf.org/rfc/rfc4122.txt)版本4. 6 | 7 | ```js 8 | const crypto = require('crypto'); 9 | const UUIDGeneratorNode = () => 10 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 11 | (c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16) 12 | ); 13 | ``` 14 | 15 | ```js 16 | UUIDGeneratorNode(); // '79c7c136-60ee-40a2-beb2-856f1feabefc' 17 | ``` -------------------------------------------------------------------------------- /snippets/bottomVisible.md: -------------------------------------------------------------------------------- 1 | ### bottomVisible 2 | 3 | Returns `true` if the bottom of the page is visible, `false` otherwise. 4 | 5 | Use `scrollY`, `scrollHeight` and `clientHeight` to determine if the bottom of the page is visible. 6 | 7 | ```js 8 | const bottomVisible = () => 9 | document.documentElement.clientHeight + window.scrollY >= 10 | (document.documentElement.scrollHeight || document.documentElement.clientHeight); 11 | ``` 12 | 13 | ```js 14 | bottomVisible(); // true 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/differenceWith.md: -------------------------------------------------------------------------------- 1 | ### differenceWith 2 | 3 | Filters out all values from an array for which the comparator function does not return `true`. 4 | 5 | Use `Array.filter()` and `Array.findIndex()` to find the appropriate values. 6 | 7 | ```js 8 | const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1); 9 | ``` 10 | 11 | ```js 12 | differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b)); // [1, 1.2] 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/extendHex.zh.md: -------------------------------------------------------------------------------- 1 | ### extendhex 2 | 3 | 将3位数的颜色代码扩展为6位数的颜色代码. 4 | 5 | 使用`array.map()`,`string.split()`和`array.join()`加入映射数组,将3位rgb注释的十六进制颜色代码转换为6位数形式. `array.slice()`是用来删除`#`从字符串开始,因为它被添加一次. 6 | 7 | ```js 8 | const extendHex = shortHex => 9 | '#' + 10 | shortHex 11 | .slice(shortHex.startsWith('#') ? 1 : 0) 12 | .split('') 13 | .map(x => x + x) 14 | .join(''); 15 | ``` 16 | 17 | ```js 18 | extendHex('#03f'); // '#0033ff' 19 | extendHex('05a'); // '#0055aa' 20 | ``` -------------------------------------------------------------------------------- /snippets/hammingDistance.md: -------------------------------------------------------------------------------- 1 | ### hammingDistance 2 | 3 | Calculates the Hamming distance between two values. 4 | 5 | Use XOR operator (`^`) to find the bit difference between the two numbers, convert to a binary string using `toString(2)`. 6 | Count and return the number of `1`s in the string, using `match(/1/g)`. 7 | 8 | ```js 9 | const hammingDistance = (num1, num2) => ((num1 ^ num2).toString(2).match(/1/g) || '').length; 10 | ``` 11 | 12 | ```js 13 | hammingDistance(2, 3); // 1 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/isPrimitive.zh.md: -------------------------------------------------------------------------------- 1 | ### isprimitive 2 | 3 | 返回一个布尔值,判断传入的值是否为原始值. 4 | 5 | 使用`array.includes()`在一个非原始类型的字符串数组上,提供使用的类型`类型`. 以来`typeof null`评估`'目的'`,需要直接比较. 6 | 7 | ```js 8 | const isPrimitive = val => !['object', 'function'].includes(typeof val) ƜƜ val === null; 9 | ``` 10 | 11 | ```js 12 | isPrimitive(null); // true 13 | isPrimitive(50); // true 14 | isPrimitive('Hello!'); // true 15 | isPrimitive(false); // true 16 | isPrimitive(Symbol()); // true 17 | isPrimitive([]); // false 18 | ``` -------------------------------------------------------------------------------- /snippets/isTravisCI.md: -------------------------------------------------------------------------------- 1 | ### isTravisCI 2 | 3 | Checks if the current environment is [Travis CI](https://travis-ci.org/). 4 | 5 | Checks if the current environment has the `TRAVIS` and `CI` environment variables ([reference](https://docs.travis-ci.com/user/environment-variables/#Default-Environment-Variables)). 6 | 7 | ```js 8 | const isTravisCI = () => 'TRAVIS' in process.env && 'CI' in process.env; 9 | ``` 10 | 11 | ```js 12 | isTravisCI(); // true (if code is running on Travis CI) 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/scrollToTop.zh.md: -------------------------------------------------------------------------------- 1 | ### 滚动到顶部 2 | 3 | 平滑滚动到页面的顶部. 4 | 5 | 从顶部使用距离`document.documentelement.scrolltop`要么`的document.body.scrollTop`. 从顶部的距离的一小部分. `使用`window.requestanimationframe()滚动动画. 6 | 7 | ```js 8 | const scrollToTop = () => { 9 | const c = document.documentElement.scrollTop ƜƜ document.body.scrollTop; 10 | if (c > 0) { 11 | window.requestAnimationFrame(scrollToTop); 12 | window.scrollTo(0, c - c / 8); 13 | } 14 | }; 15 | ``` 16 | 17 | ```js 18 | scrollToTop(); 19 | ``` -------------------------------------------------------------------------------- /snippets/truncateString.md: -------------------------------------------------------------------------------- 1 | ### truncateString 2 | 3 | Truncates a string up to a specified length. 4 | 5 | Determine if the string's `length` is greater than `num`. 6 | Return the string truncated to the desired length, with `'...'` appended to the end or the original string. 7 | 8 | ```js 9 | const truncateString = (str, num) => 10 | str.length > num ? str.slice(0, num > 3 ? num - 3 : num) + '...' : str; 11 | ``` 12 | 13 | ```js 14 | truncateString('boomerang', 7); // 'boom...' 15 | ``` 16 | -------------------------------------------------------------------------------- /snippets/validateNumber.md: -------------------------------------------------------------------------------- 1 | ### validateNumber 2 | 3 | Returns `true` if the given value is a number, `false` otherwise. 4 | 5 | Use `!isNaN()` in combination with `parseFloat()` to check if the argument is a number. 6 | Use `isFinite()` to check if the number is finite. 7 | Use `Number()` to check if the coercion holds. 8 | 9 | ```js 10 | const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n; 11 | ``` 12 | 13 | ```js 14 | validateNumber('10'); // true 15 | ``` 16 | -------------------------------------------------------------------------------- /test/call/call.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const call = require('./call.js'); 3 | 4 | test('Testing call', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof call === 'function', 'call is a Function'); 8 | //t.deepEqual(call(args..), 'Expected'); 9 | //t.equal(call(args..), 'Expected'); 10 | //t.false(call(args..), 'Expected'); 11 | //t.throws(call(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/flip/flip.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const flip = require('./flip.js'); 3 | 4 | test('Testing flip', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof flip === 'function', 'flip is a Function'); 8 | //t.deepEqual(flip(args..), 'Expected'); 9 | //t.equal(flip(args..), 'Expected'); 10 | //t.false(flip(args..), 'Expected'); 11 | //t.throws(flip(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/hide/hide.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const hide = require('./hide.js'); 3 | 4 | test('Testing hide', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof hide === 'function', 'hide is a Function'); 8 | //t.deepEqual(hide(args..), 'Expected'); 9 | //t.equal(hide(args..), 'Expected'); 10 | //t.false(hide(args..), 'Expected'); 11 | //t.throws(hide(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/once/once.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const once = require('./once.js'); 3 | 4 | test('Testing once', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof once === 'function', 'once is a Function'); 8 | //t.deepEqual(once(args..), 'Expected'); 9 | //t.equal(once(args..), 'Expected'); 10 | //t.false(once(args..), 'Expected'); 11 | //t.throws(once(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/pull/pull.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const pull = require('./pull.js'); 3 | 4 | test('Testing pull', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof pull === 'function', 'pull is a Function'); 8 | //t.deepEqual(pull(args..), 'Expected'); 9 | //t.equal(pull(args..), 'Expected'); 10 | //t.false(pull(args..), 'Expected'); 11 | //t.throws(pull(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/show/show.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const show = require('./show.js'); 3 | 4 | test('Testing show', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof show === 'function', 'show is a Function'); 8 | //t.deepEqual(show(args..), 'Expected'); 9 | //t.equal(show(args..), 'Expected'); 10 | //t.false(show(args..), 'Expected'); 11 | //t.throws(show(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/initialize2DArray.md: -------------------------------------------------------------------------------- 1 | ### initialize2DArray 2 | 3 | Initializes a 2D array of given width and height and value. 4 | 5 | Use `Array.map()` to generate h rows where each is a new array of size w initialize with value. If the value is not provided, default to `null`. 6 | 7 | ```js 8 | const initialize2DArray = (w, h, val = null) => 9 | Array.from({ length: h }).map(() => Array.from({ length: w }).fill(val)); 10 | ``` 11 | 12 | ```js 13 | initialize2DArray(2, 2, 0); // [[0,0], [0,0]] 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/averageBy.zh.md: -------------------------------------------------------------------------------- 1 | ### averageby 2 | 3 | 在使用提供的函数将每个元素映射到一个值之后,返回数组的平均值. 4 | 5 | 使用`array.map()`将每个元素映射到返回的值`FN`,`array.reduce()`将每个值添加到一个累加器,用一个值初始化`0`,除以`长度`的数组. 6 | 7 | ```js 8 | const averageBy = (arr, fn) => 9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) / 10 | arr.length; 11 | ``` 12 | 13 | ```js 14 | averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5 15 | averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5 16 | ``` -------------------------------------------------------------------------------- /test/elementIsVisibleInViewport/elementIsVisibleInViewport.js: -------------------------------------------------------------------------------- 1 | module.exports = elementIsVisibleInViewport = (el, partiallyVisible = false) => { 2 | const { top, left, bottom, right } = el.getBoundingClientRect(); 3 | const { innerHeight, innerWidth } = window; 4 | return partiallyVisible 5 | ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && 6 | ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) 7 | : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; 8 | }; -------------------------------------------------------------------------------- /test/prettyBytes/prettyBytes.js: -------------------------------------------------------------------------------- 1 | module.exports = prettyBytes = (num, precision = 3, addSpace = true) => { 2 | const UNITS = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; 3 | if (Math.abs(num) < 1) return num + (addSpace ? ' ' : '') + UNITS[0]; 4 | const exponent = Math.min(Math.floor(Math.log10(num < 0 ? -num : num) / 3), UNITS.length - 1); 5 | const n = Number(((num < 0 ? -num : num) / 1000 ** exponent).toPrecision(precision)); 6 | return (num < 0 ? '-' : '') + n + (addSpace ? ' ' : '') + UNITS[exponent]; 7 | }; -------------------------------------------------------------------------------- /snippets/hasFlags.zh.md: -------------------------------------------------------------------------------- 1 | ### hasflags 2 | 3 | 检查当前进程的参数是否包含指定的标志. 4 | 5 | 使用`array.every()`和`array.includes()`检查是否`process.argv`包含所有指定的标志. 使用正则表达式来测试指定的标志是否带有前缀`-`要么`-`并相应地加上前缀. 6 | 7 | ```js 8 | const hasFlags = (...flags) => 9 | flags.every(flag => process.argv.includes(/^-{1,2}/.test(flag) ? flag : '--' + flag)); 10 | ``` 11 | 12 | ```js 13 | // node myScript.js -s --test --cool=true 14 | hasFlags('-s'); // true 15 | hasFlags('--test', 'cool=true', '-s'); // true 16 | hasFlags('special'); // false 17 | ``` -------------------------------------------------------------------------------- /snippets/mapObject.zh.md: -------------------------------------------------------------------------------- 1 | ### MapObject的 2 | 3 | 使用函数将数组的值映射到对象,其中键 - 值对由原始值作为键和映射值组成. 4 | 5 | 使用匿名内部函数作用域来声明未定义的内存空间,使用闭包来存储返回值. `使用新的`排列将函数的映射存储在数据集上,使用逗号运算符返回第二个步骤,而不需要从一个上下文移动到另一个上下文(由于关闭和操作顺序). 6 | 7 | ```js 8 | const mapObject = (arr, fn) => 9 | (a => ( 10 | (a = [arr, arr.map(fn)]), a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {}) 11 | ))(); 12 | ``` 13 | 14 | ```js 15 | const squareIt = arr => mapObject(arr, a => a * a); 16 | squareIt([1, 2, 3]); // { 1: 1, 2: 4, 3: 9 } 17 | ``` -------------------------------------------------------------------------------- /test/defer/defer.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const defer = require('./defer.js'); 3 | 4 | test('Testing defer', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof defer === 'function', 'defer is a Function'); 8 | //t.deepEqual(defer(args..), 'Expected'); 9 | //t.equal(defer(args..), 'Expected'); 10 | //t.false(defer(args..), 'Expected'); 11 | //t.throws(defer(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/maxBy/maxBy.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const maxBy = require('./maxBy.js'); 3 | 4 | test('Testing maxBy', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof maxBy === 'function', 'maxBy is a Function'); 8 | //t.deepEqual(maxBy(args..), 'Expected'); 9 | //t.equal(maxBy(args..), 'Expected'); 10 | //t.false(maxBy(args..), 'Expected'); 11 | //t.throws(maxBy(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/merge/merge.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const merge = require('./merge.js'); 3 | 4 | test('Testing merge', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof merge === 'function', 'merge is a Function'); 8 | //t.deepEqual(merge(args..), 'Expected'); 9 | //t.equal(merge(args..), 'Expected'); 10 | //t.false(merge(args..), 'Expected'); 11 | //t.throws(merge(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/minBy/minBy.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const minBy = require('./minBy.js'); 3 | 4 | test('Testing minBy', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof minBy === 'function', 'minBy is a Function'); 8 | //t.deepEqual(minBy(args..), 'Expected'); 9 | //t.equal(minBy(args..), 'Expected'); 10 | //t.false(minBy(args..), 'Expected'); 11 | //t.throws(minBy(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/sleep/sleep.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const sleep = require('./sleep.js'); 3 | 4 | test('Testing sleep', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof sleep === 'function', 'sleep is a Function'); 8 | //t.deepEqual(sleep(args..), 'Expected'); 9 | //t.equal(sleep(args..), 'Expected'); 10 | //t.false(sleep(args..), 'Expected'); 11 | //t.throws(sleep(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/sumBy/sumBy.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const sumBy = require('./sumBy.js'); 3 | 4 | test('Testing sumBy', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof sumBy === 'function', 'sumBy is a Function'); 8 | //t.deepEqual(sumBy(args..), 'Expected'); 9 | //t.equal(sumBy(args..), 'Expected'); 10 | //t.false(sumBy(args..), 'Expected'); 11 | //t.throws(sumBy(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/sdbm.md: -------------------------------------------------------------------------------- 1 | ### sbdm 2 | 3 | Hashes the input string into a whole number. 4 | 5 | Use `String.split('')` and `Array.reduce()` to create a hash of the input string, utilizing bit shifting. 6 | 7 | ```js 8 | const sdbm = str => { 9 | let arr = str.split(''); 10 | return arr.reduce( 11 | (hashCode, currentVal) => 12 | (hashCode = currentVal.charCodeAt(0) + (hashCode << 6) + (hashCode << 16) - hashCode), 13 | 0 14 | ); 15 | }; 16 | ``` 17 | 18 | ```js 19 | sdbm('name'); // -3521204949 20 | ``` 21 | -------------------------------------------------------------------------------- /snippets/countBy.zh.md: -------------------------------------------------------------------------------- 1 | ### countby 2 | 3 | 根据给定的函数对数组的元素进行分组,并返回每个组中元素的数量. 4 | 5 | 使用`array.map()`将数组的值映射到函数或属性name.use`array.reduce()`创建一个对象,其中的密钥是从映射的结果中产生的. 6 | 7 | ```js 8 | const countBy = (arr, fn) => 9 | arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => { 10 | acc[val] = (acc[val] ƜƜ 0) + 1; 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2} 17 | countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1} 18 | ``` -------------------------------------------------------------------------------- /snippets/getURLParameters.zh.md: -------------------------------------------------------------------------------- 1 | ### geturlparameters 2 | 3 | 返回一个包含当前url参数的对象. 4 | 5 | 使用`string.match()`用适当的正则表达式来获得所有的键值对,`array.reduce()`将它们映射并组合成单个对象`location.search`作为适用于当前的理由`网址`. 6 | 7 | ```js 8 | const getURLParameters = url => 9 | url 10 | .match(/([^?=&]+)(=([^&]*))/g) 11 | .reduce((a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a), {}); 12 | ``` 13 | 14 | ```js 15 | getURLParameters('http://url.com/page?name=Adam&surname=Smith'); // {name: 'Adam', surname: 'Smith'} 16 | ``` -------------------------------------------------------------------------------- /snippets/lowercaseKeys.zh.md: -------------------------------------------------------------------------------- 1 | ### lowercasekeys 2 | 3 | 从指定的对象创建一个新的对象,其中所有的键都是小写的. 4 | 5 | 使用`object.keys()`和`array.reduce()`从指定的对象创建一个新的对象. 将原始对象中的每个键转换为小写,使用`string.tolowercase()`. 6 | 7 | ```js 8 | const lowercaseKeys = obj => 9 | Object.keys(obj).reduce((acc, key) => { 10 | acc[key.toLowerCase()] = obj[key]; 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | const myObj = { Name: 'Adam', sUrnAME: 'Smith' }; 17 | const myObjLower = lowercaseKeys(myObj); // {name: 'Adam', surname: 'Smith'}; 18 | ``` -------------------------------------------------------------------------------- /snippets/nthElement.md: -------------------------------------------------------------------------------- 1 | ### nthElement 2 | 3 | Returns the nth element of an array. 4 | 5 | Use `Array.slice()` to get an array containing the nth element at the first place. 6 | If the index is out of bounds, return `[]`. 7 | Omit the second argument, `n`, to get the first element of the array. 8 | 9 | ```js 10 | const nthElement = (arr, n = 0) => (n > 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]; 11 | ``` 12 | 13 | ```js 14 | nthElement(['a', 'b', 'c'], 1); // 'b' 15 | nthElement(['a', 'b', 'b'], -3); // 'a' 16 | ``` 17 | -------------------------------------------------------------------------------- /test/README/README.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const README = require('./README.js'); 3 | 4 | test('Testing README', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof README === 'function', 'README is a Function'); 8 | //t.deepEqual(README(args..), 'Expected'); 9 | //t.equal(README(args..), 'Expected'); 10 | //t.false(README(args..), 'Expected'); 11 | //t.throws(README(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/sample/sample.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const sample = require('./sample.js'); 3 | 4 | test('Testing sample', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof sample === 'function', 'sample is a Function'); 8 | //t.deepEqual(sample(args..), 'Expected'); 9 | //t.equal(sample(args..), 'Expected'); 10 | //t.false(sample(args..), 'Expected'); 11 | //t.throws(sample(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/sumPower.zh.md: -------------------------------------------------------------------------------- 1 | ### sumpower 2 | 3 | 返回所有数字的幂的和`开始`至`结束`(包括两端). 4 | 5 | 使用`array.fill()`创建目标范围内所有数字的数组,`array.map()`和指数运算符(`**`)把他们提高到`功率`和`array.reduce()`把它们加在一起. 第二个参数,`功率`,使用默认的权力`2`. 第三个参数,`开始`,使用默认的起始值`1`. 6 | 7 | ```js 8 | const sumPower = (end, power = 2, start = 1) => 9 | Array(end + 1 - start) 10 | .fill(0) 11 | .map((x, i) => (i + start) ** power) 12 | .reduce((a, b) => a + b, 0); 13 | ``` 14 | 15 | ```js 16 | sumPower(10); // 385 17 | sumPower(10, 3); //3025 18 | sumPower(10, 3, 5); //2925 19 | ``` -------------------------------------------------------------------------------- /snippets/symmetricDifference.md: -------------------------------------------------------------------------------- 1 | ### symmetricDifference 2 | 3 | Returns the symmetric difference between two arrays. 4 | 5 | Create a `Set` from each array, then use `Array.filter()` on each of them to only keep values not contained in the other. 6 | 7 | ```js 8 | const symmetricDifference = (a, b) => { 9 | const sA = new Set(a), 10 | sB = new Set(b); 11 | return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))]; 12 | }; 13 | ``` 14 | 15 | ```js 16 | symmetricDifference([1, 2, 3], [1, 2, 4]); // [3,4] 17 | ``` 18 | -------------------------------------------------------------------------------- /test/collatz/collatz.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const collatz = require('./collatz.js'); 3 | 4 | test('Testing collatz', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof collatz === 'function', 'collatz is a Function'); 8 | //t.deepEqual(collatz(args..), 'Expected'); 9 | //t.equal(collatz(args..), 'Expected'); 10 | //t.false(collatz(args..), 'Expected'); 11 | //t.throws(collatz(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/countBy/countBy.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const countBy = require('./countBy.js'); 3 | 4 | test('Testing countBy', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof countBy === 'function', 'countBy is a Function'); 8 | //t.deepEqual(countBy(args..), 'Expected'); 9 | //t.equal(countBy(args..), 'Expected'); 10 | //t.false(countBy(args..), 'Expected'); 11 | //t.throws(countBy(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/factors/factors.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const factors = require('./factors.js'); 3 | 4 | test('Testing factors', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof factors === 'function', 'factors is a Function'); 8 | //t.deepEqual(factors(args..), 'Expected'); 9 | //t.equal(factors(args..), 'Expected'); 10 | //t.false(factors(args..), 'Expected'); 11 | //t.throws(factors(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/httpGet/httpGet.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const httpGet = require('./httpGet.js'); 3 | 4 | test('Testing httpGet', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof httpGet === 'function', 'httpGet is a Function'); 8 | //t.deepEqual(httpGet(args..), 'Expected'); 9 | //t.equal(httpGet(args..), 'Expected'); 10 | //t.false(httpGet(args..), 'Expected'); 11 | //t.throws(httpGet(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/httpPut/httpPut.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const httpPut = require('./httpPut.js'); 3 | 4 | test('Testing httpPut', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof httpPut === 'function', 'httpPut is a Function'); 8 | //t.deepEqual(httpPut(args..), 'Expected'); 9 | //t.equal(httpPut(args..), 'Expected'); 10 | //t.false(httpPut(args..), 'Expected'); 11 | //t.throws(httpPut(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/mapKeys/mapKeys.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const mapKeys = require('./mapKeys.js'); 3 | 4 | test('Testing mapKeys', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof mapKeys === 'function', 'mapKeys is a Function'); 8 | //t.deepEqual(mapKeys(args..), 'Expected'); 9 | //t.equal(mapKeys(args..), 'Expected'); 10 | //t.false(mapKeys(args..), 'Expected'); 11 | //t.throws(mapKeys(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/memoize/memoize.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const memoize = require('./memoize.js'); 3 | 4 | test('Testing memoize', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof memoize === 'function', 'memoize is a Function'); 8 | //t.deepEqual(memoize(args..), 'Expected'); 9 | //t.equal(memoize(args..), 'Expected'); 10 | //t.false(memoize(args..), 'Expected'); 11 | //t.throws(memoize(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/shuffle/shuffle.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const shuffle = require('./shuffle.js'); 3 | 4 | test('Testing shuffle', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof shuffle === 'function', 'shuffle is a Function'); 8 | //t.deepEqual(shuffle(args..), 'Expected'); 9 | //t.equal(shuffle(args..), 'Expected'); 10 | //t.false(shuffle(args..), 'Expected'); 11 | //t.throws(shuffle(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /snippets/isPrime.md: -------------------------------------------------------------------------------- 1 | ### isPrime 2 | 3 | Checks if the provided integer is a prime number. 4 | 5 | Check numbers from `2` to the square root of the given number. 6 | Return `false` if any of them divides the given number, else return `true`, unless the number is less than `2`. 7 | 8 | ```js 9 | const isPrime = num => { 10 | const boundary = Math.floor(Math.sqrt(num)); 11 | for (var i = 2; i <= boundary; i++) if (num % i == 0) return false; 12 | return num >= 2; 13 | }; 14 | ``` 15 | 16 | ```js 17 | isPrime(11); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /snippets/mapValues.zh.md: -------------------------------------------------------------------------------- 1 | ### mapvalues 2 | 3 | 使用与提供的对象相同的键创建对象,并通过为每个值运行提供的功能生成值. 4 | 5 | 使用`object.keys(OBJ)`遍历对象的keys.use`array.reduce()`使用相同的键和映射值创建一个新的对象`FN`. 6 | 7 | ```js 8 | const mapValues = (obj, fn) => 9 | Object.keys(obj).reduce((acc, k) => { 10 | acc[k] = fn(obj[k], k, obj); 11 | return acc; 12 | }, {}); 13 | ``` 14 | 15 | ```js 16 | const users = { 17 | fred: { user: 'fred', age: 40 }, 18 | pebbles: { user: 'pebbles', age: 1 } 19 | }; 20 | mapValues(users, u => u.age); // { fred: 40, pebbles: 1 } 21 | ``` -------------------------------------------------------------------------------- /snippets/maxBy.md: -------------------------------------------------------------------------------- 1 | ### maxBy 2 | 3 | Returns the maximum value of an array, after mapping each element to a value using the provided function. 4 | 5 | Use `Array.map()` to map each element to the value returned by `fn`, `Math.max()` to get the maximum value. 6 | 7 | ```js 8 | const maxBy = (arr, fn) => Math.max(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 9 | ``` 10 | 11 | ```js 12 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 13 | maxBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/minBy.md: -------------------------------------------------------------------------------- 1 | ### minBy 2 | 3 | Returns the minimum value of an array, after mapping each element to a value using the provided function. 4 | 5 | Use `Array.map()` to map each element to the value returned by `fn`, `Math.min()` to get the maximum value. 6 | 7 | ```js 8 | const minBy = (arr, fn) => Math.min(...arr.map(typeof fn === 'function' ? fn : val => val[fn])); 9 | ``` 10 | 11 | ```js 12 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 8 13 | minBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 8 14 | ``` 15 | -------------------------------------------------------------------------------- /snippets/truthCheckCollection.md: -------------------------------------------------------------------------------- 1 | ### truthCheckCollection 2 | 3 | Checks if the predicate (second argument) is truthy on all elements of a collection (first argument). 4 | 5 | Use `Array.every()` to check if each passed object has the specified property and if it returns a truthy value. 6 | 7 | ```js 8 | const truthCheckCollection = (collection, pre) => collection.every(obj => obj[pre]); 9 | ``` 10 | 11 | ```js 12 | truthCheckCollection([{ user: 'Tinky-Winky', sex: 'male' }, { user: 'Dipsy', sex: 'male' }], 'sex'); // true 13 | ``` 14 | -------------------------------------------------------------------------------- /snippets/UUIDGeneratorBrowser.md: -------------------------------------------------------------------------------- 1 | ### UUIDGeneratorBrowser 2 | 3 | Generates a UUID in a browser. 4 | 5 | Use `crypto` API to generate a UUID, compliant with [RFC4122](https://www.ietf.org/rfc/rfc4122.txt) version 4. 6 | 7 | ```js 8 | const UUIDGeneratorBrowser = () => 9 | ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => 10 | (c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16) 11 | ); 12 | ``` 13 | 14 | ```js 15 | UUIDGeneratorBrowser(); // '7982fcfe-5721-4632-bede-6000885be57d' 16 | ``` 17 | -------------------------------------------------------------------------------- /snippets/flatten.zh.md: -------------------------------------------------------------------------------- 1 | ### 弄平 2 | 3 | 将阵列变平直到指定的深度. 4 | 5 | 使用递归,递减`深度`用于每个深度级别1`array.reduce()`和`array.concat()`合并元素或数组.base的情况下,为`深度`等于`1`停止递归. 第二个参数,`深度`只能将其平坦化`1`(单一平坦). 6 | 7 | ```js 8 | const flatten = (arr, depth = 1) => 9 | depth != 1 10 | ? arr.reduce((a, v) => a.concat(Array.isArray(v) ? flatten(v, depth - 1) : v), []) 11 | : arr.reduce((a, v) => a.concat(v), []); 12 | ``` 13 | 14 | ```js 15 | flatten([1, [2], 3, 4]); // [1, 2, 3, 4] 16 | flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8] 17 | ``` -------------------------------------------------------------------------------- /snippets/forEachRight.md: -------------------------------------------------------------------------------- 1 | ### forEachRight 2 | 3 | Executes a provided function once for each array element, starting from the array's last element. 4 | 5 | Use `Array.slice(0)` to clone the given array, `Array.reverse()` to reverse it and `Array.forEach()` to iterate over the reversed array. 6 | 7 | ```js 8 | const forEachRight = (arr, callback) => 9 | arr 10 | .slice(0) 11 | .reverse() 12 | .forEach(callback); 13 | ``` 14 | 15 | ```js 16 | forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1' 17 | ``` 18 | -------------------------------------------------------------------------------- /snippets/isValidJSON.md: -------------------------------------------------------------------------------- 1 | ### isValidJSON 2 | 3 | Checks if the provided argument is a valid JSON. 4 | 5 | Use `JSON.parse()` and a `try... catch` block to check if the provided argument is a valid JSON. 6 | 7 | ```js 8 | const isValidJSON = obj => { 9 | try { 10 | JSON.parse(obj); 11 | return true; 12 | } catch (e) { 13 | return false; 14 | } 15 | }; 16 | ``` 17 | 18 | ```js 19 | isValidJSON('{"name":"Adam","age":20}'); // true 20 | isValidJSON('{"name":"Adam",age:"20"}'); // false 21 | isValidJSON(null); // true 22 | ``` 23 | -------------------------------------------------------------------------------- /snippets/palindrome.zh.md: -------------------------------------------------------------------------------- 1 | ### 回文 2 | 3 | 回报`真正`如果给定的字符串是回文,`假`除此以外. 4 | 5 | 转换字符串`string.tolowercase()`并使用`与string.replace()`从中删除非字母数字字符. 然后,`string.split( '')`成个人角色,`array.reverse()`,`的string.join( '')`并在转换之后与原始的非反转字符串进行比较`string.tolowercase()`. 6 | 7 | ```js 8 | const palindrome = str => { 9 | const s = str.toLowerCase().replace(/[\W_]/g, ''); 10 | return ( 11 | s === 12 | s 13 | .split('') 14 | .reverse() 15 | .join('') 16 | ); 17 | }; 18 | ``` 19 | 20 | ```js 21 | palindrome('taco cat'); // true 22 | ``` -------------------------------------------------------------------------------- /snippets/select.zh.md: -------------------------------------------------------------------------------- 1 | ### 选择 2 | 3 | 从一个对象中检索给定选择器指定的一组属性. 4 | 5 | 使用`array.map()`对于每个选择器,`string.split( '')`分裂每个选择器和`array.reduce()`得到它所表示的价值. 6 | 7 | ```js 8 | const select = (from, ...selectors) => 9 | [...selectors].map(s => s.split('.').reduce((prev, cur) => prev && prev[cur], from)); 10 | ``` 11 | 12 | ```js 13 | const obj = { selector: { to: { val: 'val to select' } } }; 14 | select(obj, 'selector.to.val'); // ['val to select'] 15 | select(obj, 'selector.to.val', 'selector.to'); // ['val to select', { val: 'val to select' }] 16 | ``` -------------------------------------------------------------------------------- /snippets/yesNo.md: -------------------------------------------------------------------------------- 1 | ### yesNo 2 | 3 | Returns `true` if the string is `y`/`yes` or `false` if the string is `n`/`no`. 4 | 5 | Use `RegExp.test()` to check if the string evaluates to `y/yes` or `n/no`. 6 | Omit the second argument, `def` to set the default answer as `no`. 7 | 8 | ```js 9 | const yesNo = (val, def = false) => 10 | /^(y|yes)$/i.test(val) ? true : /^(n|no)$/i.test(val) ? false : def; 11 | ``` 12 | 13 | ```js 14 | yesNo('Y'); // true 15 | yesNo('yes'); // true 16 | yesNo('No'); // false 17 | yesNo('Foo', true); // true 18 | ``` 19 | -------------------------------------------------------------------------------- /test/colorize/colorize.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const colorize = require('./colorize.js'); 3 | 4 | test('Testing colorize', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof colorize === 'function', 'colorize is a Function'); 8 | //t.deepEqual(colorize(args..), 'Expected'); 9 | //t.equal(colorize(args..), 'Expected'); 10 | //t.false(colorize(args..), 'Expected'); 11 | //t.throws(colorize(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/distance/distance.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const distance = require('./distance.js'); 3 | 4 | test('Testing distance', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof distance === 'function', 'distance is a Function'); 8 | //t.deepEqual(distance(args..), 'Expected'); 9 | //t.equal(distance(args..), 'Expected'); 10 | //t.false(distance(args..), 'Expected'); 11 | //t.throws(distance(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/findLast/findLast.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const findLast = require('./findLast.js'); 3 | 4 | test('Testing findLast', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof findLast === 'function', 'findLast is a Function'); 8 | //t.deepEqual(findLast(args..), 'Expected'); 9 | //t.equal(findLast(args..), 'Expected'); 10 | //t.false(findLast(args..), 'Expected'); 11 | //t.throws(findLast(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/getStyle/getStyle.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const getStyle = require('./getStyle.js'); 3 | 4 | test('Testing getStyle', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof getStyle === 'function', 'getStyle is a Function'); 8 | //t.deepEqual(getStyle(args..), 'Expected'); 9 | //t.equal(getStyle(args..), 'Expected'); 10 | //t.false(getStyle(args..), 'Expected'); 11 | //t.throws(getStyle(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/hasClass/hasClass.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const hasClass = require('./hasClass.js'); 3 | 4 | test('Testing hasClass', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof hasClass === 'function', 'hasClass is a Function'); 8 | //t.deepEqual(hasClass(args..), 'Expected'); 9 | //t.equal(hasClass(args..), 'Expected'); 10 | //t.false(hasClass(args..), 'Expected'); 11 | //t.throws(hasClass(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/hasFlags/hasFlags.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const hasFlags = require('./hasFlags.js'); 3 | 4 | test('Testing hasFlags', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof hasFlags === 'function', 'hasFlags is a Function'); 8 | //t.deepEqual(hasFlags(args..), 'Expected'); 9 | //t.equal(hasFlags(args..), 'Expected'); 10 | //t.false(hasFlags(args..), 'Expected'); 11 | //t.throws(hasFlags(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/httpPost/httpPost.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const httpPost = require('./httpPost.js'); 3 | 4 | test('Testing httpPost', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof httpPost === 'function', 'httpPost is a Function'); 8 | //t.deepEqual(httpPost(args..), 'Expected'); 9 | //t.equal(httpPost(args..), 'Expected'); 10 | //t.false(httpPost(args..), 'Expected'); 11 | //t.throws(httpPost(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/isEven/isEven.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const isEven = require('./isEven.js'); 3 | 4 | test('Testing isEven', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof isEven === 'function', 'isEven is a Function'); 8 | t.equal(isEven(4), true, '4 is even number'); 9 | t.false(isEven(5), false, '5 is not an even number'); 10 | //t.deepEqual(isEven(args..), 'Expected'); 11 | //t.throws(isEven(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/redirect/redirect.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const redirect = require('./redirect.js'); 3 | 4 | test('Testing redirect', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof redirect === 'function', 'redirect is a Function'); 8 | //t.deepEqual(redirect(args..), 'Expected'); 9 | //t.equal(redirect(args..), 'Expected'); 10 | //t.false(redirect(args..), 'Expected'); 11 | //t.throws(redirect(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/runAsync/runAsync.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const runAsync = require('./runAsync.js'); 3 | 4 | test('Testing runAsync', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof runAsync === 'function', 'runAsync is a Function'); 8 | //t.deepEqual(runAsync(args..), 'Expected'); 9 | //t.equal(runAsync(args..), 'Expected'); 10 | //t.false(runAsync(args..), 'Expected'); 11 | //t.throws(runAsync(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/setStyle/setStyle.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const setStyle = require('./setStyle.js'); 3 | 4 | test('Testing setStyle', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof setStyle === 'function', 'setStyle is a Function'); 8 | //t.deepEqual(setStyle(args..), 'Expected'); 9 | //t.equal(setStyle(args..), 'Expected'); 10 | //t.false(setStyle(args..), 'Expected'); 11 | //t.throws(setStyle(args..), 'Expected'); 12 | t.end(); 13 | }); -------------------------------------------------------------------------------- /test/solveRPN/solveRPN.test.js: -------------------------------------------------------------------------------- 1 | const test = require('tape'); 2 | const solveRPN = require('./solveRPN.js'); 3 | 4 | test('Testing solveRPN', (t) => { 5 | //For more information on all the methods supported by tape 6 | //Please go to https://github.com/substack/tape 7 | t.true(typeof solveRPN === 'function', 'solveRPN is a Function'); 8 | //t.deepEqual(solveRPN(args..), 'Expected'); 9 | //t.equal(solveRPN(args..), 'Expected'); 10 | //t.false(solveRPN(args..), 'Expected'); 11 | //t.throws(solveRPN(args..), 'Expected'); 12 | t.end(); 13 | }); --------------------------------------------------------------------------------