Skip to content

Instantly share code, notes, and snippets.

@friendlyanon
Created May 20, 2019 17:58
Show Gist options
  • Save friendlyanon/4cc4ba97d3cfcad63c7f311b3b6b7676 to your computer and use it in GitHub Desktop.
Save friendlyanon/4cc4ba97d3cfcad63c7f311b3b6b7676 to your computer and use it in GitHub Desktop.
something
const limits = [
{ "x<": [90, 8] },
{ "x<": [80, 7.9] },
];
const re = /^x?([<>]=?)$|^([<>]=?)x$/i;
const comparators = {
"<": (a, b) => a < b,
"<=": (a, b) => a <= b,
">": (a, b) => a > b,
">=": (a, b) => a >= b,
};
const callers = [
(fn, a, b) => fn(b, a),
(fn, a, b) => fn(a, b),
];
function getFirstKey(obj) {
for (const key in obj) return key;
throw new TypeError("Empty object");
}
function processMatch(slice) {
const idx = slice[0] == null ? 1 : 0;
return { caller: callers[idx], comparator: comparators[slice[idx]] };
}
function parser(obj) {
const key = getFirstKey(obj);
const { 0: limit, 1: value } = obj[key];
const match = key.match(re);
if (match == null) throw new TypeError("Invalid key");
const { caller, comparator } = processMatch(match.slice(1));
return function(element) {
if (caller(comparator, limit, element)) {
this.value = value;
return true;
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment