127個常用的JS代碼片段,每段代碼花30秒就能看懂(六)


大家好,今天我繼續給大家分享本系列文章的最後一部分,感謝你對本系列文章的持續關注,希望對你的日常工作有所幫助。

106、shuffle

使用 Fisher–Yates shuffle 洗牌算法對數組的內容進行隨機排序,生成新的數組。

什麼是 Fisher–Yates shuffle 洗牌算法? 算法是一個用來將一個有限集合生成一個隨機排列的算法(數組隨機排序)。這個算法生成的隨機排列是等概率的。同時這個算法非常高效。

更多關於 Fisher–Yates shuffle 洗牌算法的內容,你可以點擊文末原文鏈接查看。

const shuffle = ([...arr]) => {
  let m = arr.length;
  while (m) {
    const i = Math.floor(Math.random() * m--);
    [arr[m], arr[i]] = [arr[i], arr[m]];
  }
  return arr;
};

const foo = [1, 2, 3];
shuffle(foo); // [2, 3, 1], foo = [1, 2, 3]

107、similarity

查找兩個數組之間的交集。

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

similarity([1, 2, 3], [1, 2, 4]); // [1, 2]

108、sleep

用於延遲異步函數的執行。

const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));

async function sleepyWork() {
  console.log("I'm going to sleep for 1 second.");
  await sleep(1000);
  console.log('I woke up after 1 second.');
}

109、smoothScroll

用於讓指定的DOM節點平滑滾動到可視區域。

const smoothScroll = element =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });
  
smoothScroll('#fooBar'); 
// scrolls smoothly to the element with the id fooBar
smoothScroll('.fooBar'); 
// scrolls smoothly to the first element with a class of fooBar

110、sortCharactersInString

將單詞的內容按照字母的順序進行重新排序。

const sortCharactersInString = str => [...str].sort((a, b) => a.localeCompare(b)).join('');

sortCharactersInString('cabbage'); 
// 'aabbceg'

111、splitLines

用於將一段字符串按照“換行符”分割成數組進行輸出。

const splitLines = str => str.split(/\r?\n/);
splitLines('This\nis a\nmultiline\nstring.\n'); 
// ['This', 'is a', 'multiline', 'string.' , '']

112、stripHTMLTags

格式化去掉 HTML 代碼內容,輸出文本內容。

const stripHTMLTags = str => str.replace(/<[^>]*>/g, '');

stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); 
// 'lorem ipsum'

113、sum

用於計算數字之和。

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

sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10

114、tail

用於獲取數組除第一個元素之外的所有元素,如果數組只有一個元素,則返回本數組。

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

tail([1, 2, 3]); // [2,3]
tail([1]); // [1]

115、take

從數組開始位置截取n個元素,生成新的數組。

const take = (arr, n = 1) => arr.slice(0, n);

take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3], 0); // []

116、takeRight

從數組開始末尾截取n個元素,生成新的數組。

const takeRight = (arr, n = 1) => arr.slice(arr.length - n, arr.length);

takeRight([1, 2, 3], 2); // [ 2, 3 ]
takeRight([1, 2, 3]); // [3]

117、timeTaken

用來計算函數執行的時間。

const timeTaken = callback => {
  console.time('timeTaken');
  const r = callback();
  console.timeEnd('timeTaken');
  return r;
};

timeTaken(() => Math.pow(2, 10)); 
// 1024, (logged): timeTaken: 0.02099609375ms

118、times

按照指定的次數,進行回調函數。

const times = (n, fn, context = undefined) => {
  let i = 0;
  while (fn.call(context, i) !== false && ++i < n) {}
};

var output = '';
times(5, i => (output += i));
console.log(output); // 01234

119、toCurrency

此段代碼用於按照指定的貨幣類型格式化貨幣數字。

const toCurrency = (n, curr, LanguageFormat = undefined) =>
  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
  
toCurrency(123456.789, 'EUR'); 
// €123,456.79  | currency: Euro | currencyLangFormat: Local
toCurrency(123456.789, 'USD', 'en-us'); 
// $123,456.79  | currency: US Dollar | currencyLangFormat: English (United States)
toCurrency(123456.789, 'USD', 'fa'); 
// ۱۲۳٬۴۵۶٫۷۹ ؜$ | currency: US Dollar | currencyLangFormat: Farsi
toCurrency(322342436423.2435, 'JPY'); 
// ¥322,342,436,423 | currency: Japanese Yen | currencyLangFormat: Local
toCurrency(322342436423.2435, 'JPY', 'fi'); 
// 322 342 436 423 ¥ | currency: Japanese Yen | currencyLangFormat: Finnish

120、toDecimalMark

用於格式化數字,將其轉換成逗號分隔的數字字符串。

const toDecimalMark = num => num.toLocaleString('en-US');

toDecimalMark(12305030388.9087); 
// "12,305,030,388.909"

121、toggleClass

使用 element.classList.toggle() 來切換元素中指定樣式類。

const toggleClass = (el, className) => el.classList.toggle(className);

toggleClass(document.querySelector('p.special'), 'special'); 
// The paragraph will not have the 'special' class anymore

122、tomorrow

用於獲取明天的日期。

const tomorrow = () => {
  let t = new Date();
  t.setDate(t.getDate() + 1);
  return t.toISOString().split('T')[0];
};

tomorrow(); 
// 2019-09-08 (if current date is 2018-09-08)

123、unfold

基於初始值,和步長生成一個新的數組。

const unfold = (fn, seed) => {
  let result = [],
    val = [null, seed];
  while ((val = fn(val[1]))) result.push(val[0]);
  return result;
};

var f = n => (n > 50 ? false : [-n, n + 10]);
unfold(f, 10); 
// [-10, -20, -30, -40, -50]

124、union

合併兩個數組,並刪除重複的內容。

const union = (a, b) => Array.from(new Set([...a, ...b]));
union([1, 2, 3], [4, 3, 2]);
// [1,2,3,4]

125、uniqueElements

使用 ES6 的 set 和 …rest 運算去除數組中重複的元素。

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

uniqueElements([1, 2, 2, 3, 4, 4, 5]); 
// [1, 2, 3, 4, 5]

126. validateNumber

用於檢查參數類型是否是數字。

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

validateNumber('10'); // true

127. words

將一段英文字符串拆分成單詞數組(去除一些特殊符號)。

const words = (str, pattern = /[^a-zA-Z-]+/) => str.split(pattern).filter(Boolean);

words('I love javaScript!!'); 
// ["I", "love", "javaScript"]
words('python, javaScript & coffee'); 
// ["python", "javaScript", "coffee"]

小節

今天的內容就和大家分享到這裏,本系列文章到此結束,感謝你的閱讀。如果你喜歡我的分享,麻煩給個關注、點贊加轉發哦,你的支持,就是我分享的動力,後續會持續分享代碼片段,歡迎持續關注。

本文原作者:Fatos Morina 來源網站:medium 注:並非直譯

相關閱讀

127個常用的JS代碼片段,每段代碼花30秒就能看懂(一)

127個常用的JS代碼片段,每段代碼花30秒就能看懂(二)

127個常用的JS代碼片段,每段代碼花30秒就能看懂(三)

127個常用的JS代碼片段,每段代碼花30秒就能看懂(四)

127個常用的JS代碼片段,每段代碼花30秒就能看懂(五)

專注分享當下最實用的前端技術。關注前端達人,與達人一起學習進步!

長按關注"前端達人"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章