JavaScript 工具函數大全(新)

前言

一線大廠筆試題靈感來源javascript

目錄:html

  • 第一部分:數組
  • 第二部分:函數
  • 第三部分:字符串
  • 第四部分:對象
  • 第五部分:數字
  • 第六部分:瀏覽器操做及其它

篩選自如下兩篇文章:前端

本來只想篩選下上面的那篇文章,在精簡掉了部分多餘且無用的工具函數後,感受不夠。因而順藤摸瓜,找到了原地址: 30 seconds of codejava

而後將全部代碼段都看了遍,篩選瞭如下一百多段代碼片斷,並加入了部分本身的理解。 node

另外, 本文工具函數的命名很是值得借鑑。

1. 第一部分:數組

1. all:布爾全等判斷

const all = (arr, fn = Boolean) => arr.every(fn);

all([4, 2, 3], x => x > 1); // true
all([1, 2, 3]); // true
複製代碼

2. allEqual:檢查數組各項相等

const allEqual = arr => arr.every(val => val === arr[0]);

allEqual([1, 2, 3, 4, 5, 6]); // false
allEqual([1, 1, 1, 1]); // true
複製代碼

3. approximatelyEqual:約等於

const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;

approximatelyEqual(Math.PI / 2.0, 1.5708); // true
複製代碼

4. arrayToCSV:數組轉CSV格式(帶空格的字符串)

const arrayToCSV = (arr, delimiter = ',') =>
  arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
  
arrayToCSV([['a', 'b'], ['c', 'd']]); // '"a","b"\n"c","d"'
arrayToCSV([['a', 'b'], ['c', 'd']], ';'); // '"a";"b"\n"c";"d"'
複製代碼

5. arrayToHtmlList:數組轉li列表

此代碼段將數組的元素轉換爲<li>標籤,並將其附加到給定ID的列表中。git

const arrayToHtmlList = (arr, listID) =>
  (el => (
    (el = document.querySelector('#' + listID)),
    (el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
  ))();
  
arrayToHtmlList(['item 1', 'item 2'], 'myListID');
複製代碼

6. average:平均數

const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;
average(...[1, 2, 3]); // 2
average(1, 2, 3); // 2
複製代碼

7. averageBy:數組對象屬性平均數

此代碼段將獲取數組對象屬性的平均值github

const averageBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
  arr.length;
  
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], o => o.n); // 5
averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
複製代碼

8. bifurcate:拆分斷言後的數組

能夠根據每一個元素返回的值,使用reduce()push() 將元素添加到第二次參數fn中 。web

const bifurcate = (arr, filter) =>
  arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
bifurcate(['beep', 'boop', 'foo', 'bar'], [true, true, false, true]); 
// [ ['beep', 'boop', 'bar'], ['foo'] ]
複製代碼

9. castArray:其它類型轉數組

const castArray = val => (Array.isArray(val) ? val : [val]);

castArray('foo'); // ['foo']
castArray([1]); // [1]
castArray(1); // [1]
複製代碼

10. compact:去除數組中的無效/無用值

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
// [ 1, 2, 3, 'a', 's', 34 ]
複製代碼

11. countOccurrences:檢測數值出現次數

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
複製代碼

12. deepFlatten:遞歸扁平化數組

const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));

deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]
複製代碼

13. difference:尋找差別(並返回第一個數組獨有的)

此代碼段查找兩個數組之間的差別,並返回第一個數組獨有的。正則表達式

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

difference([1, 2, 3], [1, 2, 4]); // [3]
複製代碼

14. differenceBy:先執行再尋找差別

在將給定函數應用於兩個列表的每一個元素以後,此方法返回兩個數組之間的差別。算法

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

differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [1.2]
differenceBy([{ x: 2 }, { x: 1 }], [{ x: 1 }], v => v.x); // [ { x: 2 } ]
複製代碼

15. dropWhile:刪除不符合條件的值

此代碼段從數組頂部開始刪除元素,直到傳遞的函數返回爲true

const dropWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
  return arr;
};

dropWhile([1, 2, 3, 4], n => n >= 3); // [3,4]
複製代碼

16. flatten:指定深度扁平化數組

此代碼段第二參數可指定深度。

const flatten = (arr, depth = 1) =>
  arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);

flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]
複製代碼

17. indexOfAll:返回數組中某值的全部索引

此代碼段可用於獲取數組中某個值的全部索引,若是此值中未包含該值,則返回一個空數組。

const indexOfAll = (arr, val) => arr.reduce((acc, el, i) => (el === val ? [...acc, i] : acc), []);

indexOfAll([1, 2, 3, 1, 2, 3], 1); // [0,3]
indexOfAll([1, 2, 3], 4); // []
複製代碼

18. intersection:兩數組的交集

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

intersection([1, 2, 3], [4, 3, 2]); // [2, 3]
複製代碼

19. intersectionWith:兩數組都符合條件的交集

此片斷可用於在對兩個數組的每一個元素執行了函數以後,返回兩個數組中存在的元素列表。

const intersectionBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.filter(x => s.has(fn(x)));
};

intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [2.1]
複製代碼

20. intersectionWith:先比較後返回交集

const intersectionWith = (a, b, comp) => a.filter(x => b.findIndex(y => comp(x, y)) !== -1);

intersectionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b)); // [1.5, 3, 0]
複製代碼

21. minN:返回指定長度的升序數組

const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);

minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1,2]
複製代碼

22. negate:根據條件反向篩選

const negate = func => (...args) => !func(...args);

[1, 2, 3, 4, 5, 6].filter(negate(n => n % 2 === 0)); // [ 1, 3, 5 ]
複製代碼

23. randomIntArrayInRange:生成兩數之間指定長度的隨機數組

const randomIntArrayInRange = (min, max, n = 1) =>
  Array.from({ length: n }, () => Math.floor(Math.random() * (max - min + 1)) + min);
  
randomIntArrayInRange(12, 35, 10); // [ 34, 14, 27, 17, 30, 27, 20, 26, 21, 14 ]
複製代碼

24. sample:在指定數組中獲取隨機數

const sample = arr => arr[Math.floor(Math.random() * arr.length)];

sample([3, 7, 9, 11]); // 9
複製代碼

25. sampleSize:在指定數組中獲取指定長度的隨機數

此代碼段可用於從數組中獲取指定長度的隨機數,直至窮盡數組。 使用Fisher-Yates算法對數組中的元素進行隨機選擇。

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

sampleSize([1, 2, 3], 2); // [3,1]
sampleSize([1, 2, 3], 4); // [2,3,1]
複製代碼

26. shuffle:「洗牌」 數組

此代碼段使用Fisher-Yates算法隨機排序數組的元素。

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]
複製代碼

27. nest:根據parent_id生成樹結構(阿里一面真題)

根據每項的parent_id,生成具體樹形結構的對象。

const nest = (items, id = null, link = 'parent_id') =>
  items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: nest(items, item.id) }));
複製代碼

用法:

const comments = [
  { id: 1, parent_id: null },
  { id: 2, parent_id: 1 },
  { id: 3, parent_id: 1 },
  { id: 4, parent_id: 2 },
  { id: 5, parent_id: 4 }
];
const nestedComments = nest(comments); // [{ id: 1, parent_id: null, children: [...] }]
複製代碼

強烈建議去理解這個的實現,由於這是我親身遇到的阿里一面真題:

2. 第二部分:函數

1. attempt:捕獲函數運行異常

該代碼段執行一個函數,返回結果或捕獲的錯誤對象。

onst attempt = (fn, ...args) => {
  try {
    return fn(...args);
  } catch (e) {
    return e instanceof Error ? e : new Error(e);
  }
};
var elements = attempt(function(selector) {
  return document.querySelectorAll(selector);
}, '>_>');
if (elements instanceof Error) elements = []; // elements = []
複製代碼

2. defer:推遲執行

此代碼段延遲了函數的執行,直到清除了當前調用堆棧。

const defer = (fn, ...args) => setTimeout(fn, 1, ...args);

defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
複製代碼

3. runPromisesInSeries:運行多個Promises

const runPromisesInSeries = ps => ps.reduce((p, next) => p.then(next), Promise.resolve());
const delay = d => new Promise(r => setTimeout(r, d));

runPromisesInSeries([() => delay(1000), () => delay(2000)]);
//依次執行每一個Promises ,總共須要3秒鐘才能完成
複製代碼

4. 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
複製代碼

5. createEventHub:簡單的發佈/訂閱模式

建立一個發佈/訂閱(發佈-訂閱)事件集線,有emitonoff方法。

  1. 使用Object.create(null)建立一個空的hub對象。
  2. emit,根據event參數解析處理程序數組,而後.forEach()經過傳入數據做爲參數來運行每一個處理程序。
  3. on,爲事件建立一個數組(若不存在則爲空數組),而後.push()將處理程序添加到該數組。
  4. off,用.findIndex()在事件數組中查找處理程序的索引,並使用.splice()刪除。
const createEventHub = () => ({
  hub: Object.create(null),
  emit(event, data) {
    (this.hub[event] || []).forEach(handler => handler(data));
  },
  on(event, handler) {
    if (!this.hub[event]) this.hub[event] = [];
    this.hub[event].push(handler);
  },
  off(event, handler) {
    const i = (this.hub[event] || []).findIndex(h => h === handler);
    if (i > -1) this.hub[event].splice(i, 1);
    if (this.hub[event].length === 0) delete this.hub[event];
  }
});
複製代碼

用法:

const handler = data => console.log(data);
const hub = createEventHub();
let increment = 0;

// 訂閱,監聽不一樣事件
hub.on('message', handler);
hub.on('message', () => console.log('Message event fired'));
hub.on('increment', () => increment++);

// 發佈:發出事件以調用全部訂閱給它們的處理程序,並將數據做爲參數傳遞給它們
hub.emit('message', 'hello world'); // 打印 'hello world''Message event fired'
hub.emit('message', { hello: 'world' }); // 打印 對象 和 'Message event fired'
hub.emit('increment'); // increment = 1

// 中止訂閱
hub.off('message', handler);
複製代碼

6. memoize:緩存函數

經過實例化一個Map對象來建立一個空的緩存。

經過檢查輸入值的函數輸出是否已緩存,返回存儲一個參數的函數,該參數將被提供給已記憶的函數;若是沒有,則存儲並返回它。

const memoize = fn => {
  const cache = new Map();
  const cached = function(val) {
    return cache.has(val) ? cache.get(val) : cache.set(val, fn.call(this, val)) && cache.get(val);
  };
  cached.cache = cache;
  return cached;
};
複製代碼

Ps: 這個版本可能不是很清晰,還有Vue源碼版的:

/**
 * Create a cached version of a pure function.
 */
export function cached<F: Function> (fn: F): F {
  const cache = Object.create(null)
  return (function cachedFn (str: string) {
    const hit = cache[str]
    return hit || (cache[str] = fn(str))
  }: any)
}
複製代碼

7. once:只調用一次的函數

const once = fn => {
  let called = false
  return function () {
    if (!called) {
      called = true
      fn.apply(this, arguments)
    }
  }
};
複製代碼

用法:

const startApp = function(event) {
  console.log(this, event); // document.body, MouseEvent
};
document.body.addEventListener('click', once(startApp)); // 只執行一次startApp
複製代碼

8. flattenObject:以鍵的路徑扁平化對象

使用遞歸。

  1. 利用Object.keys(obj)聯合Array.prototype.reduce(),以每片葉子節點轉換爲扁平的路徑節點。
  2. 若是鍵的值是一個對象,則函數使用調用適當的自身prefix以建立路徑Object.assign()
  3. 不然,它將適當的前綴鍵值對添加到累加器對象。
  4. prefix除非您但願每一個鍵都有一個前綴,不然應始終省略第二個參數。
const flattenObject = (obj, prefix = '') =>
  Object.keys(obj).reduce((acc, k) => {
    const pre = prefix.length ? prefix + '.' : '';
    if (typeof obj[k] === 'object') Object.assign(acc, flattenObject(obj[k], pre + k));
    else acc[pre + k] = obj[k];
    return acc;
  }, {});
  
flattenObject({ a: { b: { c: 1 } }, d: 1 }); // { 'a.b.c': 1, d: 1 }
複製代碼

9. unflattenObject:以鍵的路徑展開對象

與上面的相反,展開對象。

const unflattenObject = obj =>
  Object.keys(obj).reduce((acc, k) => {
    if (k.indexOf('.') !== -1) {
      const keys = k.split('.');
      Object.assign(
        acc,
        JSON.parse(
          '{' +
            keys.map((v, i) => (i !== keys.length - 1 ? `"${v}":{` : `"${v}":`)).join('') +
            obj[k] +
            '}'.repeat(keys.length)
        )
      );
    } else acc[k] = obj[k];
    return acc;
  }, {});
  
unflattenObject({ 'a.b.c': 1, d: 1 }); // { a: { b: { c: 1 } }, d: 1 }
複製代碼

這個的用途,在作Tree組件或複雜表單時取值很是舒服。

3. 第三部分:字符串

1.byteSize:返回字符串的字節長度

const byteSize = str => new Blob([str]).size;

byteSize('😀'); // 4
byteSize('Hello World'); // 11
複製代碼

2. capitalize:首字母大寫

const capitalize = ([first, ...rest]) =>
  first.toUpperCase() + rest.join('');
  
capitalize('fooBar'); // 'FooBar'
capitalize('fooBar', true); // 'Foobar'
複製代碼

3. capitalizeEveryWord:每一個單詞首字母大寫

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

capitalizeEveryWord('hello world!'); // 'Hello World!'
複製代碼

4. decapitalize:首字母小寫

const decapitalize = ([first, ...rest]) =>
  first.toLowerCase() + rest.join('')

decapitalize('FooBar'); // 'fooBar'
decapitalize('FooBar'); // 'fooBar'
複製代碼

5. luhnCheck:銀行卡號碼校驗(luhn算法)

Luhn算法的實現,用於驗證各類標識號,例如信用卡號,IMEI號,國家提供商標識號等。

String.prototype.split('')結合使用,以獲取數字數組。得到最後一個數字。實施luhn算法。若是被整除,則返回,不然返回。

const luhnCheck = num => {
  let arr = (num + '')
    .split('')
    .reverse()
    .map(x => parseInt(x));
  let lastDigit = arr.splice(0, 1)[0];
  let sum = arr.reduce((acc, val, i) => (i % 2 !== 0 ? acc + val : acc + ((val * 2) % 9) || 9), 0);
  sum += lastDigit;
  return sum % 10 === 0;
};
複製代碼

用例:

luhnCheck('4485275742308327'); // true
luhnCheck(6011329933655299); //  false
luhnCheck(123456789); // false
複製代碼

補充:銀行卡號碼的校驗規則

關於luhn算法,能夠參考如下文章:

銀行卡號碼校驗算法(Luhn算法,又叫模10算法)

銀行卡號碼的校驗採用Luhn算法,校驗過程大體以下:

  1. 從右到左給卡號字符串編號,最右邊第一位是1,最右邊第二位是2,最右邊第三位是3….

  2. 從右向左遍歷,對每一位字符t執行第三個步驟,並將每一位的計算結果相加獲得一個數s。

  3. 對每一位的計算規則:若是這一位是奇數位,則返回t自己,若是是偶數位,則先將t乘以2獲得一個數n,若是n是一位數(小於10),直接返回n,不然將n的個位數和十位數相加返回。

  4. 若是s可以整除10,則此號碼有效,不然號碼無效。

由於最終的結果會對10取餘來判斷是否可以整除10,因此又叫作模10算法。

固然,仍是庫比較香: bankcardinfo

6. splitLines:將多行字符串拆分爲行數組。

使用String.prototype.split()和正則表達式匹配換行符並建立一個數組。

const splitLines = str => str.split(/\r?\n/);

splitLines('This\nis a\nmultiline\nstring.\n'); // ['This', 'is a', 'multiline', 'string.' , '']
複製代碼

7. stripHTMLTags:刪除字符串中的HTMl標籤

從字符串中刪除HTML / XML標籤。

使用正則表達式從字符串中刪除HTML / XML 標記。

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

stripHTMLTags('<p><em>lorem</em> <strong>ipsum</strong></p>'); // 'lorem ipsum'
複製代碼

4. 第四部分:對象

1. dayOfYear:當前日期天數

const dayOfYear = date =>
  Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date()); // 285
複製代碼

2. forOwn:迭代屬性並執行回調

const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
forOwn({ foo: 'bar', a: 1 }, v => console.log(v)); // 'bar', 1
複製代碼

3. Get Time From Date:返回當前24小時制時間的字符串

const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);

getColonTimeFromDate(new Date()); // "08:38:00"
複製代碼

4. Get Days Between Dates:返回日期間的天數

const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>
  (dateFinal - dateInitial) / (1000 * 3600 * 24);
  
getDaysDiffBetweenDates(new Date('2019-01-01'), new Date('2019-10-14')); // 286
複製代碼

5. is:檢查值是否爲特定類型。

const is = (type, val) => ![, null].includes(val) && val.constructor === type;

is(Array, [1]); // true
is(ArrayBuffer, new ArrayBuffer()); // true
is(Map, new Map()); // true
is(RegExp, /./g); // true
is(Set, new Set()); // true
is(WeakMap, new WeakMap()); // true
is(WeakSet, new WeakSet()); // true
is(String, ''); // true
is(String, new String('')); // true
is(Number, 1); // true
is(Number, new Number(1)); // true
is(Boolean, true); // true
is(Boolean, new Boolean(true)); // true
複製代碼

6. isAfterDate:檢查是否在某日期後

const isAfterDate = (dateA, dateB) => dateA > dateB;

isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
複製代碼

7. isBeforeDate:檢查是否在某日期前

const isBeforeDate = (dateA, dateB) => dateA < dateB;

isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
複製代碼

8 tomorrow:獲取明天的字符串格式時間

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

tomorrow(); // 2019-10-15 (若是明天是2019-10-15)
複製代碼

9. equals:全等判斷

在兩個變量之間進行深度比較以肯定它們是否全等。

此代碼段精簡的核心在於Array.prototype.every()的使用。

const equals = (a, b) => {
  if (a === b) return true;
  if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
  if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
  if (a.prototype !== b.prototype) return false;
  let keys = Object.keys(a);
  if (keys.length !== Object.keys(b).length) return false;
  return keys.every(k => equals(a[k], b[k]));
};
複製代碼

用法:

equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
複製代碼

5. 第五部分:數字

1. randomIntegerInRange:生成指定範圍的隨機整數

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

randomIntegerInRange(0, 5); // 3
複製代碼

2. randomNumberInRange:生成指定範圍的隨機小數

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

randomNumberInRange(2, 10); // 6.0211363285087005
複製代碼

3. round:四捨五入到指定位數

const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);

round(1.005, 2); // 1.01
複製代碼

4. sum:計算數組或多個數字的總和

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

sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
複製代碼

5. toCurrency:簡單的貨幣單位轉換

const toCurrency = (n, curr, LanguageFormat = undefined) =>
  Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
  
toCurrency(123456.789, 'EUR'); // €123,456.79
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79  
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423 
複製代碼

6. 第六部分:瀏覽器操做及其它

1. bottomVisible:檢查頁面底部是否可見

const bottomVisible = () =>
  document.documentElement.clientHeight + window.scrollY >=
  (document.documentElement.scrollHeight || document.documentElement.clientHeight);

bottomVisible(); // true
複製代碼

2. Create Directory:檢查建立目錄

此代碼段調用fs模塊的existsSync()檢查目錄是否存在,若是不存在,則mkdirSync()建立該目錄。

const fs = require('fs');
const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);
createDirIfNotExists('test'); 
複製代碼

3. currentURL:返回當前連接url

const currentURL = () => window.location.href;

currentURL(); // 'https://juejin.im'
複製代碼

4. distance:返回兩點間的距離

該代碼段經過計算歐幾里得距離來返回兩點之間的距離。

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

distance(1, 1, 2, 3); // 2.23606797749979
複製代碼

5. elementContains:檢查是否包含子元素

此代碼段檢查父元素是否包含子元素。

const elementContains = (parent, child) => parent !== child && parent.contains(child);

elementContains(document.querySelector('head'), document.querySelector('title')); // true
elementContains(document.querySelector('body'), document.querySelector('body')); // false
複製代碼

6. getStyle:返回指定元素的生效樣式

const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];

getStyle(document.querySelector('p'), 'font-size'); // '16px'
複製代碼

7. getType:返回值或變量的類型名

const getType = v =>
  v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();
  
getType(new Set([1, 2, 3])); // 'set'
getType([1, 2, 3]); // 'array'
複製代碼

8. hasClass:校驗指定元素的類名

const hasClass = (el, className) => el.classList.contains(className);
hasClass(document.querySelector('p.special'), 'special'); // true
複製代碼

9. hide:隱藏全部的指定標籤

const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));

hide(document.querySelectorAll('img')); // 隱藏全部<img>標籤
複製代碼

10. httpsRedirectHTTP 跳轉 HTTPS

const httpsRedirect = () => {
  if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);
};

httpsRedirect(); // 若在`http://www.baidu.com`, 則跳轉到`https://www.baidu.com`
複製代碼

11. insertAfter:在指定元素以後插入新元素

const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);

// <div id="myId">...</div> <p>after</p>
insertAfter(document.getElementById('myId'), '<p>after</p>'); 
複製代碼

12. insertBefore:在指定元素以前插入新元素

const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);

insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
複製代碼

13. isBrowser:檢查是否爲瀏覽器環境

此代碼段可用於肯定當前運行時環境是否爲瀏覽器。這有助於避免在服務器(節點)上運行前端模塊時出錯。

const isBrowser = () => ![typeof window, typeof document].includes('undefined');

isBrowser(); // true (browser)
isBrowser(); // false (Node)
複製代碼

14. isBrowserTab:檢查當前標籤頁是否活動

const isBrowserTabFocused = () => !document.hidden;

isBrowserTabFocused(); // true
複製代碼

15. nodeListToArray:轉換nodeList爲數組

const nodeListToArray = nodeList => [...nodeList];

nodeListToArray(document.childNodes); // [ <!DOCTYPE html>, html ]
複製代碼

16. Random Hexadecimal Color Code:隨機十六進制顏色

const randomHexColorCode = () => {
  let n = (Math.random() * 0xfffff * 1000000).toString(16);
  return '#' + n.slice(0, 6);
};

randomHexColorCode(); // "#e34155"
複製代碼

17. scrollToTop:平滑滾動至頂部

該代碼段可用於平滑滾動到當前頁面的頂部。

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

scrollToTop();
複製代碼

18. smoothScroll:滾動到指定元素區域

該代碼段可將指定元素平滑滾動到瀏覽器窗口的可見區域。

const smoothScroll = element =>
  document.querySelector(element).scrollIntoView({
    behavior: 'smooth'
  });
  
smoothScroll('#fooBar'); 
smoothScroll('.fooBar'); 
複製代碼

19. detectDeviceType:檢測移動/PC設備

const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';
複製代碼

20. getScrollPosition:返回當前的滾動位置

默認參數爲windowpageXOffset(pageYOffset)爲第一選擇,沒有則用scrollLeft(scrollTop)

const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

getScrollPosition(); // {x: 0, y: 200}
複製代碼

21. size:獲取不一樣類型變量的字節長度

這個的實現很是巧妙,利用Blob類文件對象的特性,獲取對象的長度。

另外,多重三元運算符,是真香。

const size = val =>
  Array.isArray(val)
    ? val.length
    : val && typeof val === 'object'
    ? val.size || val.length || Object.keys(val).length
    : typeof val === 'string'
    ? new Blob([val]).size
    : 0;

size([1, 2, 3, 4, 5]); // 5
size('size'); // 4
size({ one: 1, two: 2, three: 3 }); // 3

複製代碼

22. escapeHTML:轉義HTML

固然是用來防XSS攻擊啦。

const escapeHTML = str =>
  str.replace(
    /[&<>'"]/g, tag => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#39;', '"': '&quot;' }[tag] || tag) ); escapeHTML('<a href="#">Me & you</a>'); // '&lt;a href=&quot;#&quot;&gt;Me &amp; you&lt;/a&gt;'
複製代碼

❤️ 看完三件事

若是你以爲這篇內容對你挺有啓發,我想邀請你幫我三個小忙:

  1. 點贊,讓更多的人也能看到這篇內容(收藏不點贊,都是耍流氓 -_-)
  2. 關注公衆號「前端勸退師」,不按期分享原創知識。
  3. 也看看其它文章

也能夠來個人GitHub博客裏拿全部文章的源文件:

前端勸退指南github.com/roger-hiro/…

相關文章
相關標籤/搜索