Skip to content

Instantly share code, notes, and snippets.

@berlysia
Created December 2, 2016 19:19
Show Gist options
  • Save berlysia/8177f0e96e097fc00dd886d86622474a to your computer and use it in GitHub Desktop.
Save berlysia/8177f0e96e097fc00dd886d86622474a to your computer and use it in GitHub Desktop.
function sorter(a, b) {
if (a.value - b.value > 0) {
return 1;
} else if (a.value - b.value < 0) {
return -1;
}
return 0;
}
class Fuzzy {
constructor (values = []) {
this.values = values.sort(sorter);
}
calc (value) {
for (let i = 0, l = this.values.length; i < l; ++i) {
const curr = this.values[i];
const prev = this.values[i - 1];
if (value === curr.value) {
return curr.name;
}
if (value < curr.value) {
if (i === 0) {
return curr.name;
}
const range = curr.value - prev.value;
const ratio = (value - prev.value) / range;
return ratio < Math.random()
? prev.name
: curr.name;
}
}
return this.values[this.values.length - 1].name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment