3 * Copyright(c) 2012-2014 TJ Holowaychuk
4 * Copyright(c) 2015-2016 Douglas Christopher Wilson
15 module.exports = rangeParser
18 * Parse "Range" header `str` relative to the given file `size`.
20 * @param {Number} size
22 * @param {Object} [options]
27 function rangeParser (size, str, options) {
28 if (typeof str !== 'string') {
29 throw new TypeError('argument str must be a string')
32 var index = str.indexOf('=')
38 // split the range string
39 var arr = str.slice(index + 1).split(',')
43 ranges.type = str.slice(0, index)
46 for (var i = 0; i < arr.length; i++) {
47 var range = arr[i].split('-')
48 var start = parseInt(range[0], 10)
49 var end = parseInt(range[1], 10)
56 } else if (isNaN(end)) {
60 // limit last-byte-pos to current length
65 // invalid or unsatisifiable
66 if (isNaN(start) || isNaN(end) || start > end || start < 0) {
77 if (ranges.length < 1) {
82 return options && options.combine
83 ? combineRanges(ranges)
88 * Combine overlapping & adjacent ranges.
92 function combineRanges (ranges) {
93 var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart)
95 for (var j = 0, i = 1; i < ordered.length; i++) {
96 var range = ordered[i]
97 var current = ordered[j]
99 if (range.start > current.end + 1) {
102 } else if (range.end > current.end) {
104 current.end = range.end
105 current.index = Math.min(current.index, range.index)
109 // trim ordered array
110 ordered.length = j + 1
112 // generate combined range
113 var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex)
116 combined.type = ranges.type
122 * Map function to add index value to ranges.
126 function mapWithIndex (range, index) {
135 * Map function to remove index value from ranges.
139 function mapWithoutIndex (range) {
147 * Sort function to sort ranges by index.
151 function sortByRangeIndex (a, b) {
152 return a.index - b.index
156 * Sort function to sort ranges by start position.
160 function sortByRangeStart (a, b) {
161 return a.start - b.start