精心收集的 48 個 JavaScript 程式碼片段,僅需 30 秒就可理解

來源:互聯網
上載者:User

標籤:bind   init   dup   tran   current   字串排序   ber   github   frame   

原文:Chalarangelo  譯文:IT168

https://github.com/Chalarangelo/30-seconds-of-code#anagrams-of-string-with-duplicates

 

該項目來自於 Github 使用者 Chalarangelo,目前已在 Github 上獲得了 5000 多Star,精心收集了多達 48 個有用的 JavaScript 程式碼片段,該使用者的代碼可以讓程式員在 30 秒甚至更少的時間內理解這些經常用到的基礎演算法,來看看這些 JavaScript 代碼都傳達出了什麼吧!

 

Anagrams of string(帶有重複項)

 

使用遞迴。對於給定字串中的每個字母,為字母建立字謎。使用map()將字母與每部分字謎組合,然後使用reduce()將所有字謎組合到一個數組中,最基本情況是字串長度等於2或1。

 

const anagrams = str => {

  if (str.length <= 2) return str.length === 2 ? [str, str[1] + str[0]] : [str];

  return str.split(‘‘).reduce((acc, letter, i) =>

    acc.concat(anagrams(str.slice(0, i) + str.slice(i + 1)).map(val => letter + val)), []);

};

// anagrams(‘abc‘) -> [‘abc‘,‘acb‘,‘bac‘,‘bca‘,‘cab‘,‘cba‘]

 

數組平均數

 

使用reduce()將每個值添加到累加器,初始值為0,總和除以數組長度。

 

const average = arr => arr.reduce((acc, val) => acc + val, 0) / arr.length;

// average([1,2,3]) -> 2

 

大寫每個單詞的首字母

 

使用replace()匹配每個單詞的第一個字元,並使用toUpperCase()來將其大寫。

 

const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());

// capitalizeEveryWord(‘hello world!‘) -> ‘Hello World!‘

 

首字母大寫

 

使用slice(0,1)和toUpperCase()大寫第一個字母,slice(1)擷取字串的其餘部分。 省略lowerRest參數以保持字串的其餘部分不變,或將其設定為true以轉換為小寫。(注意:這和上一個樣本不是同一件事情)

 

const capitalize = (str, lowerRest = false) =>

  str.slice(0, 1).toUpperCase() + (lowerRest ? str.slice(1).toLowerCase() : str.slice(1));

// capitalize(‘myName‘, true) -> ‘Myname‘

 

檢查迴文

 

將字串轉換為toLowerCase(),並使用replace()從中刪除非字母的字元。然後,將其轉換為tolowerCase(),將(‘‘)拆分為單獨字元,reverse(),join(‘‘),與原始的非反轉字串進行比較,然後將其轉換為tolowerCase()。

 

const palindrome = str => {

  const s = str.toLowerCase().replace(/[\W_]/g,‘‘);

  return s === s.split(‘‘).reverse().join(‘‘);

}

// palindrome(‘taco cat‘) -> true

 

計數數組中值的出現次數

 

每次遇到數組中的特定值時,使用reduce()來遞增計數器。

 

const countOccurrences = (arr, value) => arr.reduce((a, v) => v === value ? a + 1 : a + 0, 0);

// countOccurrences([1,1,2,1,2,3], 1) -> 3

 

當前URL

 

使用window.location.href來擷取當前URL。

 

const currentUrl = _ => window.location.href;

// currentUrl() -> ‘https://google.com‘

 

Curry

 

使用遞迴。如果提供的參數(args)數量足夠,則調用傳遞函數f,否則返回一個curried函數f。

 

const curry = (fn, arity = fn.length, ...args) =>

  arity <= args.length

    ? fn(...args)

    : curry.bind(null, fn, arity, ...args);

// curry(Math.pow)(2)(10) -> 1024

// curry(Math.min, 3)(10)(50)(2) -> 2

 

Deep flatten array

 

使用遞迴,使用reduce()來擷取所有不是數組的元素,flatten每個元素都是數組。

 

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]

 

數組之間的區別

 

從b建立一個Set,然後在a上使用Array.filter(),只保留b中不包含的值。

 

const difference = (a, b) => { const s = new Set(b); return a.filter(x => !s.has(x)); };

// difference([1,2,3], [1,2]) -> [3]

 

兩點之間的距離

 

使用Math.hypot()計算兩點之間的歐幾裡德距離。

 

const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);

// distance(1,1, 2,3) -> 2.23606797749979

 

可以按數字整除

 

使用模運算子(%)來檢查餘數是否等於0。

 

const isDivisible = (dividend, divisor) => dividend % divisor === 0;

// isDivisible(6,3) -> true

 

轉義Regex

 

使用replace()來轉義特殊字元。

 

const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, ‘\\$&‘);

// escapeRegExp(‘(test)‘) -> \\(test\\)

 

偶數或奇數

 

使用Math.abs()將邏輯擴充為負數,使用模(%)運算子進行檢查。 如果數字是偶數,則返回true;如果數字是奇數,則返回false。

 

const isEven = num => num % 2 === 0;

// isEven(3) -> false

 

階乘

 

使用遞迴。如果n小於或等於1,則返回1。否則返回n和n - 1的階乘的乘積。

 

const factorial = n => n <= 1 ? 1 : n * factorial(n - 1);

// factorial(6) -> 720

 

斐波那契數組產生器

 

建立一個特定長度的空數組,初始化前兩個值(0和1)。使用Array.reduce()向數組中添加值,後面的一個數等於前面兩個數相加之和(前兩個除外)。

 

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]

 

過濾數組中的非唯一值

 

將Array.filter()用於僅包含唯一值的數組。

 

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

 

Flatten數組

 

使用reduce()來擷取數組中的所有元素,並使用concat()來使它們flatten。

 

const flatten = arr => arr.reduce((a, v) => a.concat(v), []);

// flatten([1,[2],3,4]) -> [1,2,3,4]

 

從數組中擷取最大值

 

使用Math.max()與spread運算子(...)結合得到數組中的最大值。

 

const arrayMax = arr => Math.max(...arr);

// arrayMax([10, 1, 5]) -> 10

 

從數組中擷取最小值

 

使用Math.min()與spread運算子(...)結合得到數組中的最小值。

 

const arrayMin = arr => Math.min(...arr);

// arrayMin([10, 1, 5]) -> 1

 

擷取滾動位置

 

如果已定義,請使用pageXOffset和pageYOffset,否則使用scrollLeft和scrollTop,可以省略el來使用window的預設值。

 

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}

 

最大公約數(GCD)

 

使用遞迴。基本情況是當y等於0時。在這種情況下,返回x。否則,返回y的GCD和x / y的其餘部分。

 

const gcd = (x, y) => !y ? x : gcd(y, x % y);

// gcd (8, 36) -> 4

 

Head of list

 

返回ARR[0]

 

const head = arr => arr[0];

// head([1,2,3]) -> 1

 

list初始化

 

返回arr.slice(0,-1)

 

 

const initial = arr => arr.slice(0, -1);

// initial([1,2,3]) -> [1,2]

 

用range初始化數組

 

使用Array(end-start)建立所需長度的數組,使用map()來填充範圍中的所需值,可以省略start使用預設值0。

 

const initializeArrayRange = (end, start = 0) =>

  Array.apply(null, Array(end - start)).map((v, i) => i + start);

// initializeArrayRange(5) -> [0,1,2,3,4]

 

用值初始化數組

 

使用Array(n)建立所需長度的數組,fill(v)以填充所需的值,可以忽略value使用預設值0。

 

const initializeArray = (n, value = 0) => Array(n).fill(value);

// initializeArray(5, 2) -> [2,2,2,2,2]

 

列表的最後

 

返回arr.slice(-1)[0]

 

const last = arr => arr.slice(-1)[0];

// last([1,2,3]) -> 3

 

測試功能所花費的時間

 

使用performance.now()擷取函數的開始和結束時間,console.log()所花費的時間。第一個參數是函數名,隨後的參數傳遞給函數。

 

const timeTaken = callback => {

  console.time(‘timeTaken‘);

  const r = callback();

  console.timeEnd(‘timeTaken‘);

  return r;

};

// timeTaken(() => Math.pow(2, 10)) -> 1024

// (logged): timeTaken: 0.02099609375ms

 

來自索引值對的對象

 

使用Array.reduce()來建立和按鍵組合值對。

 

const objectFromPairs = arr => arr.reduce((a, v) => (a[v[0]] = v[1], a), {});

// objectFromPairs([[‘a‘,1],[‘b‘,2]]) -> {a: 1, b: 2}

 

管道

 

使用Array.reduce()通過函數傳遞值。

 

const pipe = (...funcs) => arg => funcs.reduce((acc, func) => func(acc), arg);

// pipe(btoa, x => x.toUpperCase())("Test") -> "VGVZDA=="

 

Powerset

 

使用reduce()與map()結合來遍曆元素,並將其組合成包含所有組合的數組。

 

const powerset = arr =>

  arr.reduce((a, v) => a.concat(a.map(r => [v].concat(r))), [[]]);

// powerset([1,2]) -> [[], [1], [2], [2,1]]

 

範圍內的隨機整數

 

使用Math.random()產生一個隨機數並將其映射到所需的範圍,使用Math.floor()使其成為一個整數。

 

const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

// randomIntegerInRange(0, 5) -> 2

 

範圍內的隨機數

 

使用Math.random()產生一個隨機值,使用乘法將其映射到所需的範圍。

 

const randomInRange = (min, max) => Math.random() * (max - min) + min;

// randomInRange(2,10) -> 6.0211363285087005

 

隨機化數組的順序

 

使用sort()重新排序元素,利用Math.random()來隨機排序。

 

const shuffle = arr => arr.sort(() => Math.random() - 0.5);

// shuffle([1,2,3]) -> [2,3,1]

 

重新導向到URL

 

使用window.location.href或window.location.replace()重新導向到url。 傳遞第二個參數來類比連結點擊(true - default)或HTTP重新導向(false)。

 

const redirect = (url, asLink = true) =>

  asLink ? window.location.href = url : window.location.replace(url);

// redirect(‘https://google.com‘)

 

反轉一個字串

 

使用數組解構和Array.reverse()來顛倒字串中的字元順序。合并字元以使用join(‘‘)擷取字串。

 

const reverseString = str => [...str].reverse().join(‘‘);

// reverseString(‘foobar‘) -> ‘raboof‘

 

RGB到十六進位

 

使用按位左移運算子(<<)和toString(16),然後padStart(6,“0”)將給定的RGB參數轉換為十六進位字串以獲得6位十六進位值。

 

const rgbToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, ‘0‘);

// rgbToHex(255, 165, 1) -> ‘ffa501‘

 

滾動到頂部

 

使用document.documentElement.scrollTop或document.body.scrollTop擷取到頂部的距離。

從頂部滾動一小部分距離。

 

使用window.requestAnimationFrame()來滾動。

 

const scrollToTop = _ => {

  const c = document.documentElement.scrollTop || document.body.scrollTop;

  if (c > 0) {

    window.requestAnimationFrame(scrollToTop);

    window.scrollTo(0, c - c / 8);

  }

};

// scrollToTop()

 

隨機數組值

 

使用Array.map()和Math.random()建立一個隨機值的數組。使用Array.sort()根據隨機值對原始數組的元素進行排序。

 

 

數組之間的相似性

 

使用filter()移除不是values的一部分值,使用includes()確定。

 

const similarity = (arr, values) => arr.filter(v => values.includes(v));

// similarity([1,2,3], [1,2,4]) -> [1,2]

 

按字串排序(按字母順序排列)

 

使用split(‘‘)分割字串,sort()使用localeCompare(),使用join(‘‘)重新組合。

 

const sortCharactersInString = str =>

  str.split(‘‘).sort((a, b) => a.localeCompare(b)).join(‘‘);

// sortCharactersInString(‘cabbage‘) -> ‘aabbceg‘

 

數組總和

 

使用reduce()將每個值添加到累加器,初始化值為0。

 

const sum = arr => arr.reduce((acc, val) => acc + val, 0);

// sum([1,2,3,4]) -> 10

 

交換兩個變數的值

 

使用數組解構來交換兩個變數之間的值。

 

[varA, varB] = [varB, varA];

// [x, y] = [y, x]

 

列表的tail

 

返回arr.slice(1)

 

const tail = arr => arr.length > 1 ? arr.slice(1) : arr;

// tail([1,2,3]) -> [2,3]

// tail([1]) -> [1]

 

數組唯一值

 

使用ES6 Set和... rest操作符去掉所有重複值。

 

const unique = arr => [...new Set(arr)];

// unique([1,2,2,3,4,4,5]) -> [1,2,3,4,5]

 

URL參數

 

使用match() 與適當的Regex來獲得所有索引值對,適當的map() 。使用Object.assign()和spread運算子(...)將所有索引值對組合到一個對象中,將location.search作為參數傳遞給當前url。

 

const getUrlParameters = url =>

  url.match(/([^?=&]+)(=([^&]*))/g).reduce(

    (a, v) => (a[v.slice(0, v.indexOf(‘=‘))] = v.slice(v.indexOf(‘=‘) + 1), a), {}

  );

// getUrlParameters(‘http://url.com/page?name=Adam&surname=Smith‘) -> {name: ‘Adam‘, surname: ‘Smith‘}

 

UUID產生器

 

使用crypto API產生符合RFC4122版本4的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‘

 

驗證數字

 

使用!isNaN和parseFloat()來檢查參數是否是一個數字,使用isFinite()來檢查數字是否是有限的。

 

const validateNumber = n => !isNaN(parseFloat(n)) && isFinite(n) && Number(n) == n;

// validateNumber(‘10‘) -> true

 

翻譯多有不準確之處,感興趣的程式員可以自行到Github上查看英文原版。

精心收集的 48 個 JavaScript 程式碼片段,僅需 30 秒就可理解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.