nhb-toolbox
Version:
A versatile collection of smart, efficient, and reusable utility functions and classes for everyday development needs.
80 lines (79 loc) • 3 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNumbersInRange = getNumbersInRange;
const basics_1 = require("../array/basics");
const index_1 = require("../utils/index");
const basics_2 = require("./basics");
const guards_1 = require("./guards");
const helpers_1 = require("./helpers");
const prime_1 = require("./prime");
/**
* * Function to get numbers within a range based on the provided `NumberType` and options.
* * Returns either a string or an array of numbers based on the `getAs` property in options.
*
* @param type - The type of numbers to generate ('random', 'prime', etc.).
* @param options - Options to configure number generation, including range and formatting.
* @returns Either a string or an array of numbers.
*/
function getNumbersInRange(type = 'any', options) {
const { getAsString = false, min = 0, max = 100, includeMin = true, includeMax = true, separator = ', ', multiplesOf, } = options || {};
let output = [];
/**
* Helper function to apply range and get array of numbers in that range.
*
* @param start The start of the range.
* @param end The end of the range.
* @returns The array of numbers in the range.
*/
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' && multiplesOf !== undefined) {
console.warn('Warning: The "multiplesOf" option is ignored when the type is "prime"!');
}
switch (type) {
case 'random':
output = (0, basics_1.shuffleArray)(_applyRangeOptions(min, max).map((n) => (0, basics_2.getRandomNumber)({
min: n,
max: n,
includeMin,
includeMax,
})));
break;
case 'prime':
output = _applyRangeOptions(min, max).filter(prime_1.isPrime);
break;
case 'odd':
output = _applyRangeOptions(min, max).filter(guards_1.isOdd);
break;
case 'even':
output = _applyRangeOptions(min, max).filter(guards_1.isEven);
break;
case 'natural':
output = _applyRangeOptions(Math.max(min, 1), max);
break;
default:
output = _applyRangeOptions(min, max);
break;
}
if (type !== 'prime') {
output = (0, helpers_1._applyMultiples)(output, multiplesOf);
}
return getAsString ?
(0, index_1.convertArrayToString)(output, { separator })
: output;
}