- 所有的可能組合方式
const anagrams = str => {
if(str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];
return str.split('').reduce( (acc, letter, i) => {
anagrams(str.slice(0, i) + str.slice(i + 1)).map( val => acc.push(letter + val) );
return acc;
}, []);
}
// anagrams('abc') -> ['abc','acb','bac','bca','cab','cba']
複製程式碼
- 數字陣列的平均值
const average = arr =>
arr.reduce( (acc , val) => acc + val, 0) / arr.length;
// average([1,2,3]) -> 2
複製程式碼
- 每一個單詞首字母轉換為大寫
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
// capitalizeEveryWord('hello world!') -> 'Hello World!'
複製程式碼
- 首字母大寫
const capitalize = (str, lowerRest = false) =>
str.slice(0, 1).toUpperCase() + (lowerRest? str.slice(1).toLowerCase() : str.slice(1));
// capitalize('myName', true) -> 'Myname'
//capitalize('myName') -> 'MyName
複製程式碼
- 檢查迴文
const palindrome = str =>
str.toLowerCase().replace(/[\W_]/g,'').split('').reverse().join('') === str.toLowerCase().replace(/[\W_]/g,'');
// palindrome('taco cat') -> true
複製程式碼
- 計算陣列中指定值的出現次數
const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);
// countOccurrences([1,1,2,1,2,3], 1) -> 3
複製程式碼
- 獲取當前網址
const currentUrl = _ => window.location.href
複製程式碼
- 函式柯里化
const curry = f =>
(...args) =>
args.length >= f.length ? f(...args) : (...otherArgs) => curry(f)(...args, ...otherArgs);
// curry(Math.pow)(2)(10) -> 1024
複製程式碼
- 巢狀陣列合並
const deepFlatten = arr =>
arr.reduce( (a, v) => a.concat( Array.isArray(v) ? deepFlatten(v) : v ), []);
// deepFlatten([1,[2],[[3],4],5]) -> [1,2,3,4,5]
複製程式碼
- 去掉2個陣列的共有元素
const difference = (arr, values) => arr.filter(v => !values.includes(v));
// difference([1,2,3], [1,2]) -> [3]
複製程式碼
- 計算2點直接的距離
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
// distance(1,1, 2,3) -> 2.23606797749979
複製程式碼
- 轉義正規表示式
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// escapeRegExp('(test)') -> \\(test\\)
複製程式碼
- 斐波拉契數列
const fibonacci = n =>
Array(n).fill(0).reduce((acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),[]);
// fibonacci(5) -> [0,1,1,2,3]
複製程式碼
- 陣列去重
const unique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// unique([1,2,2,3,4,4,5]) -> [1,3,5]
複製程式碼
- 陣列合並
const flatten = arr => arr.reduce( (a, v) => a.concat(v), []);
// flatten([1,[2],3,4]) -> [1,2,3,4]
複製程式碼
- 獲取陣列中最大值
const arrayMax = arr => Math.max(...arr);
// arrayMax([10, 1, 5]) -> 10
複製程式碼
- 獲取陣列中最小值
const arrayMin = arr => Math.min(...arr);
// arrayMin([10, 1, 5]) -> 1
複製程式碼
- 獲取滾動條位置
const getScrollPos = (el = window) =>
( {x: (el.pageXOffset !== undefined) ? el.pageXOffset : el.scrollLeft,
y: (el.pageYOffset !== undefined) ? el.pageYOffset : el.scrollTop} );
// getScrollPos() -> {x: 0, y: 200}
複製程式碼
- 最大公約數
const gcd = (x , y) => !y ? x : gcd(y, x % y);
// gcd (8, 36) -> 4
複製程式碼
- 使用一組連續範圍數字初始化一個組數
const initializeArrayRange = (end, start = 0) =>
Array.apply(null, Array(end-start)).map( (v,i) => i + start );
// initializeArrayRange(5) -> [0,1,2,3,4]
複製程式碼
- 測試函式執行時間
const timeTaken = (func,...args) => {
var t0 = performance.now(), r = func(...args);
console.log(performance.now() - t0);
return r;
}
// timeTaken(Math.pow, 2, 10) -> 1024 (0.010000000009313226 logged in console)
複製程式碼
- 將鍵值對陣列轉成物件
const objectFromPairs = arr => arr.reduce((a,v) => (a[v[0]] = v[1], a), {});
// objectFromPairs([['a',1],['b',2]]) -> {a: 1, b: 2}
複製程式碼
- 管道,返回一組函式處理後的結果
const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);
// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="
複製程式碼
- 生成指定範圍的隨機整數
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
// randomIntegerInRange(0, 5) -> 2
複製程式碼
- 將陣列亂序
const randomizeOrder = arr => arr.sort( (a,b) => Math.random() >= 0.5 ? -1 : 1);
// randomizeOrder([1,2,3]) -> [1,3,2]
複製程式碼
- RGB轉16進位制值
const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
// rgbToHex(255, 165, 1) -> 'ffa501'
複製程式碼
- 回到頂部
const scrollToTop = _ => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if(c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c/8);
}
}
// scrollToTop()
複製程式碼
- 獲取2個陣列的交集
const similarity = (arr, values) => arr.filter(v => values.includes(v));
// similarity([1,2,3], [1,2,4]) -> [1,2]
複製程式碼
- 字元排序
const sortCharactersInString = str =>
str.split('').sort( (a,b) => a.localeCompare(b) ).join('');
// sortCharactersInString('cabbage') -> 'aabbceg'
複製程式碼
- 獲取url中的引數
const getUrlParameters = url =>
Object.assign(...url.match(/([^?=&]+)(=([^&]*))?/g).map(m => {[f,v] = m.split('='); return {[f]:v}}));
// getUrlParameters('http://url.com/page?name=Adam&surname=Smith') -> {name: 'Adam', surname: 'Smith'}
複製程式碼
- UUID生成
const uuid = _ =>
( [1e7]+-1e3+-4e3+-8e3+-1e11 ).replace( /[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
// uuid() -> '7982fcfe-5721-4632-bede-6000885be57d'
複製程式碼
原文地址: https://github.com/Chalarangelo/30-seconds-of-code