UNPKG

tiny-bin

Version:

A library for building tiny and beautiful command line apps.

59 lines (58 loc) 1.93 kB
/* IMPORT */ import stripAnsi from 'ansi-purge'; import { toCamelCase } from 'kasi'; import levenshtein from 'tiny-levenshtein'; import parseArgv from 'tiny-parse-argv'; /* MAIN */ const castArray = (value) => { return Array.isArray(value) ? value : [value]; }; 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 isObject = (value) => { return typeof value === 'object' && value !== null; }; 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 { castArray, getClosest, groupBy, identity, isArray, isObject, isUndefined, parseArgv, pushBack, stripAnsi, sum, toCamelCase };