@opra/common
Version:
Opra common package
42 lines (41 loc) • 1.27 kB
JavaScript
const STATUS_RANGE_PATTERN = /^([1-6]\d{2})(?:-([1-6]\d{2}))?$/;
/**
* @class HttpStatusRange
*/
export class HttpStatusRange {
start = 0;
end = 0;
constructor(arg0, arg1) {
if (arg0 && typeof arg0 === 'object') {
this.start = arg0.start || 0;
this.end = arg0.end || 0;
}
if (typeof arg0 === 'number') {
this.start = arg0;
this.end = arg1 || this.start;
}
if (typeof arg0 === 'string') {
const m = STATUS_RANGE_PATTERN.exec(arg0);
if (!m)
throw new TypeError(`"${arg0}" is not a valid Status Code range`);
this.start = parseInt(m[1], 10);
this.end = m[2] ? parseInt(m[2], 10) : this.start;
}
}
includes(statusCode) {
return statusCode >= this.start && statusCode <= this.end;
}
intersects(start, end) {
return end >= this.start && start <= this.end;
}
toString() {
if (this.start === this.end)
return String(this.start);
return String(this.start) + '-' + String(this.end);
}
toJSON() {
return !this.end || this.start === this.end
? this.start
: { start: this.start, end: this.end };
}
}