-
-
Save RanolP/86fdee0aa290830a6e21af09e610585a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const BoundType = Object.freeze({ | |
Included: 'bound_type::included', | |
Excluded: 'bound_type::excluded', | |
}); | |
class Bound { | |
constructor(type, value) { | |
this.type = type; | |
this.value = value; | |
} | |
} | |
class Interval { | |
constructor(start, end) { | |
this.start = start; | |
this.end = end; | |
} | |
contains(value) { | |
switch (this.start.type) { | |
case BoundType.Included: { | |
if (!(this.start.value <= value)) { | |
return false; | |
} | |
break; | |
} | |
case BoundType.Excluded: { | |
if (!(this.start.value < value)) { | |
return false; | |
} | |
break; | |
} | |
} | |
switch (this.end.type) { | |
case BoundType.Included: { | |
if (!(value <= this.end.value)) { | |
return false; | |
} | |
break; | |
} | |
case BoundType.Excluded: { | |
if (!(value < this.end.value)) { | |
return false; | |
} | |
break; | |
} | |
} | |
return true; | |
} | |
toString() { | |
return `${this.start.value} <${this.start.type == BoundType.Included ? '=' : ''} x <${this.end.type == BoundType.Included ? '=' : ''} ${this.end.value}` | |
} | |
} | |
function i(template, ...args) { | |
if (!template.length || !template[0]) { | |
throw new Error('Template does not provided correctly.'); | |
} | |
let startType; | |
switch (template[0][0]) { | |
case '(': { | |
startType = BoundType.Excluded; | |
break; | |
} | |
case '[': { | |
startType = BoundType.Included; | |
break; | |
} | |
default: { | |
throw new Error(`First character must be '(' or '[', but ${template[0][0]} found.`); | |
break; | |
} | |
} | |
let endType; | |
switch (template.slice(-1)[0].slice(-1)[0]) { | |
case ')': { | |
endType = BoundType.Excluded; | |
break; | |
} | |
case ']': { | |
endType = BoundType.Included; | |
break; | |
} | |
default: { | |
throw new Error(`Last character must be ')' or ']', but ${template[0][0]} found.`); | |
break; | |
} | |
} | |
const formatted = Array.from(args.keys()).reduce((acc, k) => acc + args[k] + template[k+1], template[0]); | |
const inner = formatted.slice(1, -1); | |
const arr = inner.split(','); | |
if (arr.length !== 2) { | |
throw new Error('Interval must be separated with one comma'); | |
} | |
const start = Number(arr[0]); | |
const end = Number(arr[1]); | |
if (start === NaN) { | |
throw new Error('Start value must be parsed as number'); | |
} | |
if (end === NaN) { | |
throw new Error('End value must be parsed as number'); | |
} | |
return new Interval(new Bound(startType, start), new Bound(endType, end)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment