UNPKG

nhb-toolbox

Version:

A versatile collection of smart, efficient, and reusable utility functions, classes and types for everyday development needs.

61 lines (60 loc) 2.23 kB
import { shuffleArray } from '../array/basics.js'; import { isUndefined } from '../guards/primitives.js'; import { convertArrayToString } from '../utils/index.js'; import { getRandomNumber } from './basics.js'; import { isEven, isOdd } from './guards.js'; import { _applyMultiples } from './helpers.js'; import { isPrime } from './prime.js'; export function getNumbersInRange(type = 'any', options) { const { getAsString = false, min = 0, max = 100, includeMin = true, includeMax = true, separator = ', ', multiplesOf, } = options || {}; let output = []; const _applyRangeOptions = (start, end) => { let startNumber = start; let endNumber = end; if (start > end) { [startNumber, endNumber] = [end, start]; } const numbers = []; for (let i = startNumber; i <= endNumber; i++) { if (i >= startNumber && i <= endNumber && (includeMin || i > startNumber) && (includeMax || i < endNumber)) { numbers.push(i); } } return numbers; }; if (type === 'prime' && !isUndefined(multiplesOf)) { console.warn('Warning: The "multiplesOf" option is ignored when the type is "prime"!'); } switch (type) { case 'random': output = shuffleArray(_applyRangeOptions(min, max).map((n) => getRandomNumber({ min: n, max: n, includeMin, includeMax, }))); break; case 'prime': output = _applyRangeOptions(min, max).filter(isPrime); break; case 'odd': output = _applyRangeOptions(min, max).filter(isOdd); break; case 'even': output = _applyRangeOptions(min, max).filter(isEven); break; case 'natural': output = _applyRangeOptions(Math.max(min, 1), max); break; default: output = _applyRangeOptions(min, max); break; } if (type !== 'prime') { output = _applyMultiples(output, multiplesOf); } return (getAsString ? convertArrayToString(output, { separator }) : output); }