常用JavaScript代码片段汇总

1、all
const all = (arr, fn = Boolean) => arr.every(fn);all([4, 2, 3], x => x > 1); // trueall([1, 2, 3]); // true
2、allEqual
const allEqual = arr => arr.every(val => val === arr[0]);allEqual([1, 2, 3, 4, 5, 6]); // falseallEqual([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
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
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、attempt
const 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 = []
7、average
const average = (...nums) => nums.reduce((acc, val) => acc + val, 0) / nums.length;average(...[1, 2, 3]); // 2average(1, 2, 3); // 2
8、averageBy
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); // 5averageBy([{ n: 4 }, { n: 2 }, { n: 8 }, { n: 6 }], 'n'); // 5
9、bifurcate
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'] ]
10、bifurcateBy
const bifurcateBy = (arr, fn) =>arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');// [ ['beep', 'boop', 'bar'], ['foo'] ]
11、bottomVisible
const bottomVisible = () =>document.documentElement.clientHeight + window.scrollY >=(document.documentElement.scrollHeight || document.documentElement.clientHeight);bottomVisible(); // true
12、byteSize
const byteSize = str => new Blob([str]).size;byteSize('😀'); // 4byteSize('Hello World'); // 11
13、capitalize
const capitalize = ([first, ...rest]) =>first.toUpperCase() + rest.join('');capitalize('fooBar'); // 'FooBar'capitalize('fooBar', true); // 'FooBar'
14、capitalizeEveryWord
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());capitalizeEveryWord('hello world!'); // 'Hello World!'
15、castArray
const castArray = val => (Array.isArray(val) ? val : [val]);castArray('foo'); // ['foo']castArray([1]); // [1]
16、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 ]
17、countOccurrences
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3
18、Create Directory
const fs = require('fs');const createDirIfNotExists = dir => (!fs.existsSync(dir) ? fs.mkdirSync(dir) : undefined);createDirIfNotExists('test');// creates the directory 'test', if it doesn't exist
19、currentURL
const currentURL = () => window.location.href;currentURL(); // 'https://medium.com/@fatosmorina'
20、dayOfYear
const dayOfYear = date =>Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);dayOfYear(new Date()); // 272
21、decapitalize
const decapitalize = ([first, ...rest]) =>first.toLowerCase() + rest.join('')decapitalize('FooBar'); // 'fooBar'
22、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]
23、default
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);defaults({ a: 1 }, { b: 2 }, { b: 6 }, { a: 3 }); // { a: 1, b: 2 }
24、defer
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);defer(console.log, 'a'), console.log('b'); // logs 'b' then 'a'
25、degreesToRads
const degreesToRads = deg => (deg * Math.PI) / 180.0;degreesToRads(90.0); // ~1.5708
26、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]
27、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 } ]
28、differenceWith
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);differenceWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0], (a, b) => Math.round(a) === Math.round(b));// [1, 1.2]
29、digitize
const digitize = n => [...`${n}`].map(i => parseInt(i));digitize(431); // [4, 3, 1]
30、distance
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);distance(1, 1, 2, 3); // 2.23606797749979
31、drop
const drop = (arr, n = 1) => arr.slice(n);drop([1, 2, 3]); // [2,3]drop([1, 2, 3], 2); // [3]drop([1, 2, 3], 42); // []
32、dropRight
const dropRight = (arr, n = 1) => arr.slice(0, -n);dropRight([1, 2, 3]); // [1,2]dropRight([1, 2, 3], 2); // [1]dropRight([1, 2, 3], 42); // []
33、dropRightWhile
const dropRightWhile = (arr, func) => {while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);return arr;};dropRightWhile([1, 2, 3, 4], n => n < 3); // [1, 2]
34、dropWhile
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]
35、elementContains
const elementContains = (parent, child) => parent !== child && parent.contains(child);elementContains(document.querySelector('head'), document.querySelector('title')); // trueelementContains(document.querySelector('body'), document.querySelector('body')); // false
36、filterNonUnique
const filterNonUnique = arr => [ …new Set(arr)];filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 2, 3, 4, 5]
37、findKey
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));findKey({barney: { age: 36, active: true },fred: { age: 40, active: false },pebbles: { age: 1, active: true }},o => o['active']); // 'barney'
38、findLast
const findLast = (arr, fn) => arr.filter(fn).pop();findLast([1, 2, 3, 4], n => n % 2 === 1); // 3
39、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]
40、forEachRight
const forEachRight = (arr, callback) =>arr.slice(0).reverse().forEach(callback);forEachRight([1, 2, 3, 4], val => console.log(val)); // '4', '3', '2', '1'
41、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
42、functionName
const functionName = fn => (console.debug(fn.name), fn);functionName(Math.max); // max (logged in debug channel of console)
43、getColonTimeFromDate
const getColonTimeFromDate = date => date.toTimeString().slice(0, 8);getColonTimeFromDate(new Date()); // "08:38:00"
44、getDaysDiffBetweenDates
const getDaysDiffBetweenDates = (dateInitial, dateFinal) =>(dateFinal - dateInitial) / (1000 * 3600 * 24);getDaysDiffBetweenDates(new Date('2019-01-13'), new Date('2019-01-15')); // 2
45、getStyle
const getStyle = (el, ruleName) => getComputedStyle(el)[ruleName];getStyle(document.querySelector('p'), 'font-size'); // '16px'
46、getType
const getType = v =>v === undefined ? 'undefined' : v === null ? 'null' : v.constructor.name.toLowerCase();getType(new Set([1, 2, 3])); // 'set'
47、hasClass
const hasClass = (el, className) => el.classList.contains(className);hasClass(document.querySelector('p.special'), 'special'); // true
48、head
const head = arr => arr[0];head([1, 2, 3]); // 1
49、hide
const hide = (...el) => [...el].forEach(e => (e.style.display = 'none'));hide(document.querySelectorAll('img')); // Hides all <img> elements on the page
50、httpsRedirect
const httpsRedirect = () => {if (location.protocol !== 'https:') location.replace('https://' + location.href.split('//')[1]);};httpsRedirect(); // If you are on http://mydomain.com, you are redirected to https://mydomain.com
51、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); // []
52、initial
const initial = arr => arr.slice(0, -1);initial([1, 2, 3]); // [1,2]const initial = arr => arr.slice(0, -1);initial([1, 2, 3]); // [1,2]
53、insertAfter
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);insertAfter(document.getElementById('myId'), '<p>after</p>'); // <div id="myId">...</div> <p>after</p>
54、insertBefore
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);insertBefore(document.getElementById('myId'), '<p>before</p>'); // <p>before</p> <div id="myId">...</div>
55、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]
56、intersectionBy
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]
57、intersectionBy
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]
58、is
const is = (type, val) => ![, null].includes(val) && val.constructor === type;is(Array, [1]); // trueis(ArrayBuffer, new ArrayBuffer()); // trueis(Map, new Map()); // trueis(RegExp, /./g); // trueis(Set, new Set()); // trueis(WeakMap, new WeakMap()); // trueis(WeakSet, new WeakSet()); // trueis(String, ''); // trueis(String, new String('')); // trueis(Number, 1); // trueis(Number, new Number(1)); // trueis(Boolean, true); // trueis(Boolean, new Boolean(true)); // true
59、isAfterDate
const isAfterDate = (dateA, dateB) => dateA > dateB;isAfterDate(new Date(2010, 10, 21), new Date(2010, 10, 20)); // true
60、isAnagram
const isAnagram = (str1, str2) => {const normalize = str =>str.toLowerCase().replace(/[^a-z0-9]/gi, '').split('').sort().join('');return normalize(str1) === normalize(str2);};isAnagram('iceman', 'cinema'); // true
61、isArrayLike
const isArrayLike = obj => obj != null && typeof obj[Symbol.iterator] === 'function';isArrayLike(document.querySelectorAll('.className')); // trueisArrayLike('abc'); // trueisArrayLike(null); // false
62、isBeforeDate
const isBeforeDate = (dateA, dateB) => dateA < dateB;isBeforeDate(new Date(2010, 10, 20), new Date(2010, 10, 21)); // true
63、isBoolean
const isBoolean = val => typeof val === 'boolean';isBoolean(null); // falseisBoolean(false); // true
64、getColonTimeFromDate
const isBrowser = () => ![typeof window, typeof document].includes('undefined');isBrowser(); // true (browser)isBrowser(); // false (Node)
65、isBrowserTabFocused
const isBrowserTabFocused = () => !document.hidden;isBrowserTabFocused(); // true
66、isLowerCase
const isLowerCase = str => str === str.toLowerCase();isLowerCase('abc'); // trueisLowerCase('a3@$'); // trueisLowerCase('Ab4'); // false
67、isNil
const isNil = val => val === undefined || val === null;isNil(null); // trueisNil(undefined); // true
68、isNull
const isNull = val => val === null;isNull(null); // true
69、isNumber
function isNumber(n) {return !isNaN(parseFloat(n)) && isFinite(n);}isNumber('1'); // falseisNumber(1); // true
70、isObject
const isObject = obj => obj === Object(obj);isObject([1, 2, 3, 4]); // trueisObject([]); // trueisObject(['Hello!']); // trueisObject({ a: 1 }); // trueisObject({}); // trueisObject(true); // false
71、isObjectLike
const isObjectLike = val => val !== null && typeof val === 'object';isObjectLike({}); // trueisObjectLike([1, 2, 3]); // trueisObjectLike(x => x); // falseisObjectLike(null); // false
72、isPlainObject
const isPlainObject = val => !!val && typeof val === 'object' && val.constructor === Object;isPlainObject({ a: 1 }); // trueisPlainObject(new Map()); // false
73、isPromiseLike
const isPromiseLike = obj =>obj !== null &&(typeof obj === 'object' || typeof obj === 'function') &&typeof obj.then === 'function';isPromiseLike({then: function() {return '';}}); // trueisPromiseLike(null); // falseisPromiseLike({}); // false
74、isSameDate
const isSameDate = (dateA, dateB) => dateA.toISOString() === dateB.toISOString();isSameDate(new Date(2010, 10, 20), new Date(2010, 10, 20)); // true
75、isString
const isString = val => typeof val === 'string';isString('10'); // true
76、isSymbol
const isSymbol = val => typeof val === 'symbol';isSymbol(Symbol('x')); // true
77、isUndefined
const isUndefined = val => val === undefined;isUndefined(undefined); // true
78、isUpperCase
const isUpperCase = str => str === str.toUpperCase();isUpperCase('ABC'); // trueisLowerCase('A3@$'); // trueisLowerCase('aB4'); // false
79、isValidJSON
const isValidJSON = str => {try {JSON.parse(str);return true;} catch (e) {return false;}};isValidJSON('{"name":"Adam","age":20}'); // trueisValidJSON('{"name":"Adam",age:"20"}'); // falseisValidJSON(null); // true
80、last
const last = arr => arr[arr.length - 1];last([1, 2, 3]); // 3
81、matches
onst matches = (obj, source) =>Object.keys(source).every(key => obj.hasOwnProperty(key) && obj[key] === source[key]);matches({ age: 25, hair: 'long', beard: true }, { hair: 'long', beard: true }); // truematches({ hair: 'long', beard: true }, { age: 25, hair: 'long', beard: true }); // false
82、maxDate
const maxDate = (...dates) => new Date(Math.max.apply(null, ...dates));const array = [new Date(2017, 4, 13),new Date(2018, 2, 12),new Date(2016, 0, 10),new Date(2016, 0, 9)];maxDate(array); // 2018-03-11T22:00:00.000Z
83、maxN
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);maxN([1, 2, 3]); // [3]maxN([1, 2, 3], 2); // [3,2]
84、minDate
const minDate = (...dates) => new Date(Math.min.apply(null, ...dates));const array = [new Date(2017, 4, 13),new Date(2018, 2, 12),new Date(2016, 0, 10),new Date(2016, 0, 9)];minDate(array); // 2016-01-08T22:00:00.000Z

评论
