Skip to content

Instantly share code, notes, and snippets.

@ledsun
Last active February 4, 2020 05:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ledsun/a4f731af3a55aa0a465808cebe6c7a0f to your computer and use it in GitHub Desktop.
Save ledsun/a4f731af3a55aa0a465808cebe6c7a0f to your computer and use it in GitHub Desktop.
interval notationをパースするJavaScript
// Usage: new IntervalNotation('[−3,1]').test(1) => true
// What's interval notation? see: https://www.varsitytutors.com/hotmath/hotmath_help/topics/interval-notation
class IntervalNotation {
constructor(str) {
const [left, right] = str.split(',')
if (!right) {
if (left.startsWith('[') || left.startsWith('(')) {
// Upper limit is omitted
this._lowwerCond = getLowwerCond(left)
this._upperCond = (_) => true
}
if (left.endsWith(']') || left.endsWith(')')) {
// Lowwer limit is omitted
this._lowwerCond = (_) => true
this._upperCond = getUpperCond(left)
}
} else {
this._lowwerCond = getLowwerCond(left)
this._upperCond = getUpperCond(right)
}
if (!this._lowwerCond || !this._upperCond) {
throw `${str} is not valid interval notation`
}
}
test(value) {
return this._lowwerCond(value) && this._upperCond(value)
}
}
function getLowwerCond(str) {
if (str.startsWith('[')) {
return (right) => gte(parseFloat(str.replace('[', '')), right)
}
if (str.startsWith('(')) {
return (right) => gt(new Number(str.replace('(', '')), right)
}
throw `${str} is not valid interval notation`
}
function getUpperCond(str) {
if (str.endsWith(']')) {
return (left) => gte(left, new Number(str.replace(']', '')))
}
if (str.endsWith(')')) {
return (left) => gt(left, new Number(str.replace(')', '')))
}
throw `${str} is not valid interval notation`
}
function gt(left, right) {
return left < right
}
function gte(left, right) {
return left <= right
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment