Created
December 2, 2016 19:19
-
-
Save berlysia/8177f0e96e097fc00dd886d86622474a 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
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