What is parse-numeric-range?
The parse-numeric-range npm package is a utility for parsing numeric ranges from strings. It can handle individual numbers, ranges, and combinations of both, making it useful for scenarios where you need to interpret and work with numeric ranges from user input or configuration files.
What are parse-numeric-range's main functionalities?
Parse Single Numbers
This feature allows you to parse a single number from a string and returns it as an array containing that number.
const parse = require('parse-numeric-range');
const result = parse('5');
console.log(result); // [5]
Parse Ranges
This feature allows you to parse a range of numbers from a string and returns an array containing all the numbers in that range.
const parse = require('parse-numeric-range');
const result = parse('1-5');
console.log(result); // [1, 2, 3, 4, 5]
Parse Combinations of Numbers and Ranges
This feature allows you to parse a combination of individual numbers and ranges from a string, returning an array containing all the specified numbers.
const parse = require('parse-numeric-range');
const result = parse('1-3,5,7-9');
console.log(result); // [1, 2, 3, 5, 7, 8, 9]
Other packages similar to parse-numeric-range
range-parser
The range-parser package is used to parse HTTP Range headers, which specify a range of bytes to be sent from a server. While it is more specialized for HTTP use cases, it can also handle numeric ranges but is not as general-purpose as parse-numeric-range.
node-parse-numeric-range
Parses expressions like 1-10,20-30. Returns an energetic (as opposed to lazy) array.
Supported Expressions
Comprehensive supported expression examples:
Expression | result |
---|
| [] |
1 | [1] |
1,2 | [1,2] |
-10 | [-10] |
-3,-3 | [-3, -3] |
-1-2,-2 | [-1,0,1,2,-2] |
-1--2 | [-1,-2] |
-1..2,-2 | [-1,0,1,2,-2] |
-1...3,-2 | [-1,0,1,2,-2] |
What's this useful for? Well, letting users input these sorts of things and then
making them programmatically useful.
Usage
First, npm install parse-numeric-range
.
var rangeParser = require('parse-numeric-range');
var nums = rangeParser.parse('4,6,8-10,12,14..16,18,20...23');
console.log("The first " + nums.length + " composite numbers are: " + nums.join(', '));