Codacy style changes for test files

This commit is contained in:
Angelos Chalaris
2018-08-02 13:32:50 +03:00
parent 9385ef92ad
commit 067447bdfa
338 changed files with 2641 additions and 2305 deletions

View File

@ -51,13 +51,13 @@ snippetFiles
// Grab snippet function based on code markers
const fileFunction = fileCode
.split('\n')
.map(line => line.trim())
.filter((_, i) => blockMarkers[0] < i && i < blockMarkers[1]);
.map(line => line)
.filter((_, i) => blockMarkers[0] < i && i < blockMarkers[1]).concat('');
// Grab snippet example based on code markers
const fileExample = fileCode
.split('\n')
.map(line => line.trim())
.filter((_, i) => blockMarkers[2] < i && i < blockMarkers[3]);
.map(line => line)
.filter((_, i) => blockMarkers[2] < i && i < blockMarkers[3]).concat('');
// Export template for snippetName.js
const exportFile = `${fileFunction.join('\n')}\nmodule.exports = ${fileName};`.trim();

View File

@ -1,6 +1,7 @@
const CSVToArray = (data, delimiter = ',', omitFirstRow = false) =>
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
data
.slice(omitFirstRow ? data.indexOf('\n') + 1 : 0)
.split('\n')
.map(v => v.split(delimiter));
module.exports = CSVToArray;

View File

@ -1,11 +1,12 @@
const CSVToJSON = (data, delimiter = ',') => {
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
const titles = data.slice(0, data.indexOf('\n')).split(delimiter);
return data
.slice(data.indexOf('\n') + 1)
.split('\n')
.map(v => {
const values = v.split(delimiter);
return titles.reduce((obj, title, index) => ((obj[title] = values[index]), obj), {});
});
};
module.exports = CSVToJSON;

View File

@ -1,5 +1,6 @@
const JSONToDate = arr => {
const dt = new Date(parseInt(arr.toString().substr(6)));
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
const dt = new Date(parseInt(arr.toString().substr(6)));
return `${dt.getDate()}/${dt.getMonth() + 1}/${dt.getFullYear()}`;
};
module.exports = JSONToDate;

View File

@ -1,4 +1,5 @@
const fs = require('fs');
const JSONToFile = (obj, filename) =>
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));
module.exports = JSONToFile;

View File

@ -1,11 +1,12 @@
const JSONtoCSV = (arr, columns, delimiter = ',') =>
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
[
columns.join(delimiter),
...arr.map(obj =>
columns.reduce(
(acc, key) => `${acc}${!acc.length ? '' : delimiter}"${!obj[key] ? '' : obj[key]}"`,
''
)
)
].join('\n');
module.exports = JSONtoCSV;

View File

@ -1,2 +1,3 @@
const RGBToHex = (r, g, b) => ((r << 16) + (g << 8) + b).toString(16).padStart(6, '0');
module.exports = RGBToHex;

View File

@ -1,10 +1,11 @@
const URLJoin = (...args) =>
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
args
.join('/')
.replace(/[\/]+/g, '/')
.replace(/^(.+):\//, '$1://')
.replace(/^file:/, 'file:/')
.replace(/\/(\?|&|#[^!])/g, '$1')
.replace(/\?/g, '&')
.replace('&', '?');
module.exports = URLJoin;

View File

@ -1,5 +1,6 @@
const UUIDGeneratorBrowser = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.getRandomValues(new Uint8Array(1))[0] & (15 >> (c / 4)))).toString(16)
);
module.exports = UUIDGeneratorBrowser;

View File

@ -1,6 +1,7 @@
const crypto = require('crypto');
const UUIDGeneratorNode = () =>
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
(c ^ (crypto.randomBytes(1)[0] & (15 >> (c / 4)))).toString(16)
);
module.exports = UUIDGeneratorNode;

View File

@ -1,2 +1,3 @@
const all = (arr, fn = Boolean) => arr.every(fn);
module.exports = all;

View File

@ -1,2 +1,3 @@
const any = (arr, fn = Boolean) => arr.some(fn);
module.exports = any;

View File

@ -1,2 +1,3 @@
const approximatelyEqual = (v1, v2, epsilon = 0.001) => Math.abs(v1 - v2) < epsilon;
module.exports = approximatelyEqual;

View File

@ -1,3 +1,4 @@
const arrayToCSV = (arr, delimiter = ',') =>
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
arr.map(v => v.map(x => `"${x}"`).join(delimiter)).join('\n');
module.exports = arrayToCSV;

View File

@ -1,6 +1,7 @@
const arrayToHtmlList = (arr, listID) =>
(el => (
(el = document.querySelector('#' + listID)),
(el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
))();
(el => (
(el = document.querySelector('#' + listID)),
(el.innerHTML += arr.map(item => `<li>${item}</li>`).join(''))
))();
module.exports = arrayToHtmlList;

View File

@ -1,2 +1,3 @@
const ary = (fn, n) => (...args) => fn(...args.slice(0, n));
module.exports = ary;

View File

@ -1,2 +1,3 @@
const atob = str => new Buffer(str, 'base64').toString('binary');
module.exports = atob;

View File

@ -1,8 +1,9 @@
const attempt = (fn, ...args) => {
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
try {
return fn(...args);
} catch (e) {
return e instanceof Error ? e : new Error(e);
}
};
module.exports = attempt;

View File

@ -1,2 +1,3 @@
const average = (...nums) => [...nums].reduce((acc, val) => acc + val, 0) / nums.length;
module.exports = average;

View File

@ -1,4 +1,5 @@
const averageBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => acc + val, 0) /
arr.length;
module.exports = averageBy;

View File

@ -1,3 +1,4 @@
const bifurcate = (arr, filter) =>
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
arr.reduce((acc, val, i) => (acc[filter[i] ? 0 : 1].push(val), acc), [[], []]);
module.exports = bifurcate;

View File

@ -1,3 +1,4 @@
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [[], []]);
module.exports = bifurcateBy;

View File

@ -1,8 +1,9 @@
const binarySearch = (arr, val, start = 0, end = arr.length - 1) => {
if (start > end) return -1;
const mid = Math.floor((start + end) / 2);
if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
return mid;
if (start > end) return -1;
const mid = Math.floor((start + end) / 2);
if (arr[mid] > val) return binarySearch(arr, val, start, mid - 1);
if (arr[mid] < val) return binarySearch(arr, val, mid + 1, end);
return mid;
};
module.exports = binarySearch;

View File

@ -1,5 +1,6 @@
const bind = (fn, context, ...args) =>
function() {
return fn.apply(context, args.concat(...arguments));
};
function() {
return fn.apply(context, args.concat(...arguments));
};
module.exports = bind;

View File

@ -1,10 +1,11 @@
const bindAll = (obj, ...fns) =>
fns.forEach(
fn => (
(f = obj[fn]),
(obj[fn] = function() {
return f.apply(obj);
})
)
);
fns.forEach(
fn => (
(f = obj[fn]),
(obj[fn] = function() {
return f.apply(obj);
})
)
);
module.exports = bindAll;

View File

@ -1,5 +1,6 @@
const bindKey = (context, fn, ...args) =>
function() {
return context[fn].apply(context, args.concat(...arguments));
};
function() {
return context[fn].apply(context, args.concat(...arguments));
};
module.exports = bindKey;

View File

@ -1,11 +1,12 @@
const binomialCoefficient = (n, k) => {
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
if (Number.isNaN(n) || Number.isNaN(k)) return NaN;
if (k < 0 || k > n) return 0;
if (k === 0 || k === n) return 1;
if (k === 1 || k === n - 1) return n;
if (n - k < k) k = n - k;
let res = n;
for (let j = 2; j <= k; j++) res *= (n - j + 1) / j;
return Math.round(res);
};
module.exports = binomialCoefficient;

View File

@ -1,4 +1,5 @@
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
module.exports = bottomVisible;

View File

@ -1,2 +1,3 @@
const btoa = str => new Buffer(str, 'binary').toString('base64');
module.exports = btoa;

View File

@ -1,2 +1,3 @@
const byteSize = str => new Blob([str]).size;
module.exports = byteSize;

View File

@ -1,2 +1,3 @@
const call = (key, ...args) => context => context[key](...args);
module.exports = call;

View File

@ -1,3 +1,4 @@
const capitalize = ([first, ...rest], lowerRest = false) =>
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
first.toUpperCase() + (lowerRest ? rest.join('').toLowerCase() : rest.join(''));
module.exports = capitalize;

View File

@ -1,2 +1,3 @@
const capitalizeEveryWord = str => str.replace(/\b[a-z]/g, char => char.toUpperCase());
module.exports = capitalizeEveryWord;

View File

@ -1,2 +1,3 @@
const castArray = val => (Array.isArray(val) ? val : [val]);
module.exports = castArray;

View File

@ -1,6 +1,7 @@
const chainAsync = fns => {
let curr = 0;
const next = () => fns[curr++](next);
next();
let curr = 0;
const next = () => fns[curr++](next);
next();
};
module.exports = chainAsync;

View File

@ -1,5 +1,6 @@
const chunk = (arr, size) =>
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
Array.from({ length: Math.ceil(arr.length / size) }, (v, i) =>
arr.slice(i * size, i * size + size)
);
module.exports = chunk;

View File

@ -1,2 +1,3 @@
const clampNumber = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
module.exports = clampNumber;

View File

@ -1,11 +1,12 @@
const cleanObj = (obj, keysToKeep = [], childIndicator) => {
Object.keys(obj).forEach(key => {
if (key === childIndicator) {
cleanObj(obj[key], keysToKeep, childIndicator);
} else if (!keysToKeep.includes(key)) {
delete obj[key];
}
});
return obj;
Object.keys(obj).forEach(key => {
if (key === childIndicator) {
cleanObj(obj[key], keysToKeep, childIndicator);
} else if (!keysToKeep.includes(key)) {
delete obj[key];
}
});
return obj;
};
module.exports = cleanObj;

View File

@ -1,2 +1,3 @@
const cloneRegExp = regExp => new RegExp(regExp.source, regExp.flags);
module.exports = cloneRegExp;

View File

@ -1,2 +1,3 @@
const coalesce = (...args) => args.find(_ => ![undefined, null].includes(_));
module.exports = coalesce;

View File

@ -1,2 +1,3 @@
const coalesceFactory = valid => (...args) => args.find(valid);
module.exports = coalesceFactory;

View File

@ -1,2 +1,3 @@
const collatz = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);
module.exports = collatz;

View File

@ -1,2 +1,3 @@
const collectInto = fn => (...args) => fn(args);
module.exports = collectInto;

View File

@ -1,19 +1,20 @@
const colorize = (...args) => ({
black: `\x1b[30m${args.join(' ')}`,
red: `\x1b[31m${args.join(' ')}`,
green: `\x1b[32m${args.join(' ')}`,
yellow: `\x1b[33m${args.join(' ')}`,
blue: `\x1b[34m${args.join(' ')}`,
magenta: `\x1b[35m${args.join(' ')}`,
cyan: `\x1b[36m${args.join(' ')}`,
white: `\x1b[37m${args.join(' ')}`,
bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
black: `\x1b[30m${args.join(' ')}`,
red: `\x1b[31m${args.join(' ')}`,
green: `\x1b[32m${args.join(' ')}`,
yellow: `\x1b[33m${args.join(' ')}`,
blue: `\x1b[34m${args.join(' ')}`,
magenta: `\x1b[35m${args.join(' ')}`,
cyan: `\x1b[36m${args.join(' ')}`,
white: `\x1b[37m${args.join(' ')}`,
bgBlack: `\x1b[40m${args.join(' ')}\x1b[0m`,
bgRed: `\x1b[41m${args.join(' ')}\x1b[0m`,
bgGreen: `\x1b[42m${args.join(' ')}\x1b[0m`,
bgYellow: `\x1b[43m${args.join(' ')}\x1b[0m`,
bgBlue: `\x1b[44m${args.join(' ')}\x1b[0m`,
bgMagenta: `\x1b[45m${args.join(' ')}\x1b[0m`,
bgCyan: `\x1b[46m${args.join(' ')}\x1b[0m`,
bgWhite: `\x1b[47m${args.join(' ')}\x1b[0m`
});
module.exports = colorize;

View File

@ -1,2 +1,3 @@
const compact = arr => arr.filter(Boolean);
module.exports = compact;

View File

@ -1,2 +1,3 @@
const compose = (...fns) => fns.reduce((f, g) => (...args) => f(g(...args)));
module.exports = compose;

View File

@ -1,2 +1,3 @@
const composeRight = (...fns) => fns.reduce((f, g) => (...args) => g(f(...args)));
module.exports = composeRight;

View File

@ -1,2 +1,3 @@
const converge = (converger, fns) => (...args) => converger(...fns.map(fn => fn.apply(null, args)));
module.exports = converge;

View File

@ -1,18 +1,19 @@
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
module.exports = copyToClipboard;

View File

@ -1,6 +1,7 @@
const countBy = (arr, fn) =>
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val, i) => {
acc[val] = (acc[val] || 0) + 1;
return acc;
}, {});
module.exports = countBy;

View File

@ -1,2 +1,3 @@
const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
module.exports = countOccurrences;

View File

@ -1,2 +1,3 @@
const countVowels = str => (str.match(/[aeiou]/gi) || []).length;
module.exports = countVowels;

View File

@ -1,12 +1,13 @@
const counter = (selector, start, end, step = 1, duration = 2000) => {
let current = start,
_step = (end - start) * step < 0 ? -step : step,
timer = setInterval(() => {
current += _step;
document.querySelector(selector).innerHTML = current;
if (current >= end) document.querySelector(selector).innerHTML = end;
if (current >= end) clearInterval(timer);
}, Math.abs(Math.floor(duration / (end - start))));
return timer;
let current = start,
_step = (end - start) * step < 0 ? -step : step,
timer = setInterval(() => {
current += _step;
document.querySelector(selector).innerHTML = current;
if (current >= end) document.querySelector(selector).innerHTML = end;
if (current >= end) clearInterval(timer);
}, Math.abs(Math.floor(duration / (end - start))));
return timer;
};
module.exports = counter;

View File

@ -1,6 +1,7 @@
const createElement = str => {
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
const el = document.createElement('div');
el.innerHTML = str;
return el.firstElementChild;
};
module.exports = createElement;

View File

@ -1,15 +1,16 @@
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);
}
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);
}
});
module.exports = createEventHub;

View File

@ -1,2 +1,3 @@
const currentURL = () => window.location.href;
module.exports = currentURL;

View File

@ -1,3 +1,4 @@
const curry = (fn, arity = fn.length, ...args) =>
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
arity <= args.length ? fn(...args) : curry.bind(null, fn, arity, ...args);
module.exports = curry;

View File

@ -1,8 +1,9 @@
const debounce = (fn, ms = 0) => {
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
let timeoutId;
return function(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
module.exports = debounce;

View File

@ -1,3 +1,4 @@
const decapitalize = ([first, ...rest], upperRest = false) =>
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
first.toLowerCase() + (upperRest ? rest.join('').toUpperCase() : rest.join(''));
module.exports = decapitalize;

View File

@ -1,8 +1,9 @@
const deepClone = obj => {
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
let clone = Object.assign({}, obj);
Object.keys(clone).forEach(
key => (clone[key] = typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key])
);
return Array.isArray(obj) ? (clone.length = obj.length) && Array.from(clone) : clone;
};
module.exports = deepClone;

View File

@ -1,2 +1,3 @@
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
module.exports = deepFlatten;

View File

@ -1,2 +1,3 @@
const defaults = (obj, ...defs) => Object.assign({}, obj, ...defs.reverse(), obj);
module.exports = defaults;

View File

@ -1,2 +1,3 @@
const defer = (fn, ...args) => setTimeout(fn, 1, ...args);
module.exports = defer;

View File

@ -1,2 +1,3 @@
const degreesToRads = deg => (deg * Math.PI) / 180.0;
module.exports = degreesToRads;

View File

@ -1,2 +1,3 @@
const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args);
module.exports = delay;

View File

@ -1,5 +1,6 @@
const detectDeviceType = () =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
? 'Mobile'
: 'Desktop';
module.exports = detectDeviceType;

View File

@ -1,5 +1,6 @@
const difference = (a, b) => {
const s = new Set(b);
return a.filter(x => !s.has(x));
const s = new Set(b);
return a.filter(x => !s.has(x));
};
module.exports = difference;

View File

@ -1,5 +1,6 @@
const differenceBy = (a, b, fn) => {
const s = new Set(b.map(v => fn(v)));
return a.filter(x => !s.has(fn(x)));
const s = new Set(b.map(v => fn(v)));
return a.filter(x => !s.has(fn(x)));
};
module.exports = differenceBy;

View File

@ -1,2 +1,3 @@
const differenceWith = (arr, val, comp) => arr.filter(a => val.findIndex(b => comp(a, b)) === -1);
module.exports = differenceWith;

View File

@ -1,8 +1,9 @@
const dig = (obj, target) =>
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
target in obj
? obj[target]
: Object.values(obj).reduce((acc, val) => {
if (acc !== undefined) return acc;
if (typeof val === 'object') return dig(val, target);
}, undefined);
module.exports = dig;

View File

@ -1,2 +1,3 @@
const digitize = n => [...`${n}`].map(i => parseInt(i));
module.exports = digitize;

View File

@ -1,2 +1,3 @@
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
module.exports = distance;

View File

@ -1,2 +1,3 @@
const drop = (arr, n = 1) => arr.slice(n);
module.exports = drop;

View File

@ -1,2 +1,3 @@
const dropRight = (arr, n = 1) => arr.slice(0, -n);
module.exports = dropRight;

View File

@ -1,5 +1,6 @@
const dropRightWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
while (arr.length > 0 && !func(arr[arr.length - 1])) arr = arr.slice(0, -1);
return arr;
};
module.exports = dropRightWhile;

View File

@ -1,5 +1,6 @@
const dropWhile = (arr, func) => {
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
while (arr.length > 0 && !func(arr[0])) arr = arr.slice(1);
return arr;
};
module.exports = dropWhile;

View File

@ -1,2 +1,3 @@
const elementContains = (parent, child) => parent !== child && parent.contains(child);
module.exports = elementContains;

View File

@ -1,9 +1,10 @@
const elementIsVisibleInViewport = (el, partiallyVisible = false) => {
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
const { top, left, bottom, right } = el.getBoundingClientRect();
const { innerHeight, innerWidth } = window;
return partiallyVisible
? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) &&
((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth))
: top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth;
};
module.exports = elementIsVisibleInViewport;

View File

@ -1,18 +1,19 @@
const elo = ([...ratings], kFactor = 32, selfRating) => {
const [a, b] = ratings;
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
const newRating = (rating, i) =>
(selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
}
for (let i = 0, len = ratings.length; i < len; i++) {
let j = i;
while (j < len - 1) {
j++;
[ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor);
}
}
return ratings;
const [a, b] = ratings;
const expectedScore = (self, opponent) => 1 / (1 + 10 ** ((opponent - self) / 400));
const newRating = (rating, i) =>
(selfRating || rating) + kFactor * (i - expectedScore(i ? a : b, i ? b : a));
if (ratings.length === 2) {
return [newRating(a, 1), newRating(b, 0)];
}
for (let i = 0, len = ratings.length; i < len; i++) {
let j = i;
while (j < len - 1) {
j++;
[ratings[i], ratings[j]] = elo([ratings[i], ratings[j]], kFactor);
}
}
return ratings;
};
module.exports = elo;

View File

@ -1,11 +1,12 @@
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 === null || a === undefined || b === null || b === undefined) return false;
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]));
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 === null || a === undefined || b === null || b === undefined) return false;
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]));
};
module.exports = equals;

View File

@ -1,13 +1,14 @@
const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag] || tag)
);
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;'
}[tag] || tag)
);
module.exports = escapeHTML;

View File

@ -1,2 +1,3 @@
const escapeRegExp = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
module.exports = escapeRegExp;

View File

@ -1,2 +1,3 @@
const everyNth = (arr, nth) => arr.filter((e, i) => i % nth === nth - 1);
module.exports = everyNth;

View File

@ -1,8 +1,9 @@
const extendHex = shortHex =>
'#' +
shortHex
.slice(shortHex.startsWith('#') ? 1 : 0)
.split('')
.map(x => x + x)
.join('');
'#' +
shortHex
.slice(shortHex.startsWith('#') ? 1 : 0)
.split('')
.map(x => x + x)
.join('');
module.exports = extendHex;

View File

@ -1,9 +1,10 @@
const factorial = n =>
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
n < 0
? (() => {
throw new TypeError('Negative numbers are not allowed!');
})()
: n <= 1
? 1
: n * factorial(n - 1);
module.exports = factorial;

View File

@ -1,20 +1,21 @@
const factors = (num, primes = false) => {
const isPrime = num => {
const boundary = Math.floor(Math.sqrt(num));
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
return num >= 2;
};
const isNeg = num < 0;
num = isNeg ? -num : num;
let array = Array.from({ length: num - 1 })
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
.filter(val => val);
if (isNeg)
array = array.reduce((acc, val) => {
acc.push(val);
acc.push(-val);
return acc;
}, []);
return primes ? array.filter(isPrime) : array;
const isPrime = num => {
const boundary = Math.floor(Math.sqrt(num));
for (var i = 2; i <= boundary; i++) if (num % i === 0) return false;
return num >= 2;
};
const isNeg = num < 0;
num = isNeg ? -num : num;
let array = Array.from({ length: num - 1 })
.map((val, i) => (num % (i + 2) === 0 ? i + 2 : false))
.filter(val => val);
if (isNeg)
array = array.reduce((acc, val) => {
acc.push(val);
acc.push(-val);
return acc;
}, []);
return primes ? array.filter(isPrime) : array;
};
module.exports = factors;

View File

@ -1,6 +1,7 @@
const fibonacci = n =>
Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
module.exports = fibonacci;

View File

@ -1,3 +1,4 @@
const fibonacciCountUntilNum = num =>
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
module.exports = fibonacciCountUntilNum;

View File

@ -1,8 +1,9 @@
const fibonacciUntilNum = num => {
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
let n = Math.ceil(Math.log(num * Math.sqrt(5) + 1 / 2) / Math.log((Math.sqrt(5) + 1) / 2));
return Array.from({ length: n }).reduce(
(acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
[]
);
};
module.exports = fibonacciUntilNum;

View File

@ -1,2 +1,3 @@
const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
module.exports = filterNonUnique;

View File

@ -1,3 +1,4 @@
const filterNonUniqueBy = (arr, fn) =>
arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));
module.exports = filterNonUniqueBy;

View File

@ -1,2 +1,3 @@
const findKey = (obj, fn) => Object.keys(obj).find(key => fn(obj[key], key, obj));
module.exports = findKey;

View File

@ -1,2 +1,3 @@
const findLast = (arr, fn) => arr.filter(fn).pop();
module.exports = findLast;

View File

@ -1,6 +1,7 @@
const findLastIndex = (arr, fn) =>
arr
.map((val, i) => [i, val])
.filter(([i, val]) => fn(val, i, arr))
.pop()[0];
arr
.map((val, i) => [i, val])
.filter(([i, val]) => fn(val, i, arr))
.pop()[0];
module.exports = findLastIndex;

View File

@ -1,5 +1,6 @@
const findLastKey = (obj, fn) =>
Object.keys(obj)
.reverse()
.find(key => fn(obj[key], key, obj));
Object.keys(obj)
.reverse()
.find(key => fn(obj[key], key, obj));
module.exports = findLastKey;

View File

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

View File

@ -1,8 +1,9 @@
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;
}, {});
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;
}, {});
module.exports = flattenObject;

View File

@ -1,2 +1,3 @@
const flip = fn => (first, ...rest) => fn(...rest, first);
module.exports = flip;

View File

@ -1,6 +1,7 @@
const forEachRight = (arr, callback) =>
arr
.slice(0)
.reverse()
.forEach(callback);
arr
.slice(0)
.reverse()
.forEach(callback);
module.exports = forEachRight;

View File

@ -1,2 +1,3 @@
const forOwn = (obj, fn) => Object.keys(obj).forEach(key => fn(obj[key], key, obj));
module.exports = forOwn;

Some files were not shown because too many files have changed in this diff Show More