UNPKG

tiny-bin

Version:

A library for building tiny and beautiful command line apps.

67 lines (66 loc) 2.23 kB
/* IMPORT */ import stripAnsi from 'ansi-purge'; import levenshtein from 'tiny-levenshtein'; /* MAIN */ const camelCase = (() => { const dividerRe = /[_.\s-]+/g; const prefixRe = /^[_.\s-]+/g; const upperDigitRe = /\d+[\p{Alpha}\p{N}_]/gu; const upperDividerRe = /[_.\s-]+[\p{Alpha}\p{N}_]/gu; const toUpperCase = (str) => str.toUpperCase(); return (str) => { return str.trim().toLowerCase().replace(prefixRe, '').replace(upperDigitRe, toUpperCase).replace(upperDividerRe, toUpperCase).replace(dividerRe, ''); }; })(); const castArray = (value) => { return Array.isArray(value) ? value : [value]; }; const defer = (fn) => { setTimeout(fn, 0); }; const getClosest = (values, value, maxDistance = 3, caseInsensitive = false) => { if (!values.length) return; const target = caseInsensitive ? value.toLowerCase() : value; const targets = caseInsensitive ? values.map(value => value.toLowerCase()) : values; const distances = targets.map(other => levenshtein(target, other)); const minDistance = Math.min(...distances); if (minDistance > maxDistance) return; const minDistanceIndex = distances.indexOf(minDistance); const closest = values[minDistanceIndex]; return closest; }; const groupBy = (values, iterator) => { const groups = new Map(); for (let i = 0, l = values.length; i < l; i++) { const value = values[i]; const key = iterator(value, i, values); const group = groups.get(key) || []; group.push(value); groups.set(key, group); } return groups; }; const identity = (value) => { return value; }; const isArray = (value) => { return Array.isArray(value); }; const isUndefined = (value) => { return value === undefined; }; const pushBack = (map, key) => { const value = map.get(key); if (isUndefined(value)) return map; //TODO: Technically "undefined" could be a valid key here map.delete(key); map.set(key, value); return map; }; const sum = (numbers) => { return numbers.reduce((acc, value) => acc + value, 0); }; /* EXPORT */ export { camelCase, castArray, defer, getClosest, groupBy, identity, isArray, stripAnsi, pushBack, sum };