number-ranger
Interpret ranges from strings and use them easily.
Install
Install via npm:
npm install number-ranger
API
ranger.parse(s)
Parses and transforms a string into a easily usable range.
var ranger = ; ranger;// --> [{ start: 2 }] // Add ':' to make a range between two numbersranger;// --> [{ start: 2, end: 3 }] // Create multiple ranges by separating them by ','ranger;// --> [{ start: 2, end: 3 }, { start: 4 }] // Floating numbers are fineranger;// --> [{ start: .002, end: .4 }] // -/+ infinity is represented by $ranger;// --> [{ start: 2, end: +Infinity }]ranger;// --> [{ start: -Infinity, end: 2 }] // Exclude bounds by prepending by xranger;// --> [{ start: 2, end: 4, startIncluded: false }]ranger;// --> [{ start: 2, end: 4, endIncluded: false }]
You can specify your own symbols if you want. If you use forbidden symbols or have multiple keys have the same value, any calls will return false. If you wish to use odd and/or unforeseen symbols, test carefully beforehand to make sure it works. If you use symbols like '.', '-', you may lose the ability to parse floating or negative numbers for instance.
ranger;// --> [// { start: 2, end: 4, endIncluded: false },// { start: -47, end: +Infinity }// ] ranger;// --> false
ranger.isInRange(item, ranges[, key])
Checks if item is in the given ranges.
Ranges can be a string as given for #ranger.parse(s)
, or the result of it.
A key can also be provided when item is not a number but an object, and the value of item[key] will then be compared.
var ranger = ; // Pass the result of ranger.rangeranger;// --> true // or ranger.ranger will be used implicitlyranger;// --> true ranger;// --> false ranger;// --> true // By specifying a field, it will consider item to be an object and use item[key] as the valueranger;// --> true // The order of start and end are not importantranger;// --> true // You can exclude boundsranger;// --> false
ranger.isInRangeFilter(ranges[, key])
Returns an easy filter function that removes items that wouldn't match ranger.isInRange(item, ranges)
.
Ranges can be a string as given for #ranger.parse(s)
, or the result of it.
A key can also be provided when item is not a number but an object, and the value of item[key] will then be compared.
var ranger = ; 0 1 2 3 4 5 6 7 8 9 10;// --> [0, 1, 2, 3, 4, 5] 0 1 2 3 4 5 6 7 8 9 10;// --> [0, 1, 2, 3, 4] value: 0 value: 1 value: 2 value: 3 value: 4 ;// --> [{ value: 1 }, { value: 2 }, { value: 3 }]