30 seconds of code js javascript

2022-01-24 09:42:16 浏览数 (1)

代码语言:javascript复制
const chunk = (arr, size) =>
  Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
    arr.slice(i * size, i * size   size)
  );
代码语言:javascript复制
const countBy = (arr, fn) =>
  arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
    acc[val] = (acc[val] || 0)   1;
    return acc;
  }, {});
代码语言:javascript复制
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a   1 : a), 0);
代码语言:javascript复制
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
代码语言:javascript复制
const difference = (a, b) => {
  const s = new Set(b);
  return a.filter(x => !s.has(x));
};
代码语言:javascript复制
const differenceBy = (a, b, fn) => {
  const s = new Set(b.map(fn));
  return a.map(fn).filter(el => !s.has(el));
};
代码语言:javascript复制
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
代码语言:javascript复制
const dropRight = (arr, n = 1) => arr.slice(0, -n);
代码语言:javascript复制
const dropRightWhile = (arr, func) => {
  while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
  return arr;
};
代码语言:javascript复制
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

0 人点赞