+36
-18
@@ -6,11 +6,4 @@ (function(){ | ||
| function Rater(options){ | ||
| _.defaults(this, { | ||
| factors: [], | ||
| }); | ||
| _.extend(this, options); | ||
| this.factors.push({ | ||
| weight: 1, | ||
| score: wordScore, | ||
| }); | ||
| this.setDefaultFactors(); | ||
| } | ||
@@ -20,7 +13,18 @@ | ||
| sorted: function(){ | ||
| return this.array | ||
| .map(function(d){ | ||
| return d.toLowerCase(); | ||
| }) | ||
| setDefaultFactors: function(){ | ||
| this.factors = [ | ||
| { | ||
| weight: 1, | ||
| score: Rater.wordScore.bind(this), | ||
| }, | ||
| { | ||
| weight: 0.1, | ||
| score: Rater.wordLength.bind(this), | ||
| } | ||
| ] | ||
| }, | ||
| sorted: function(array){ | ||
| return (array || this.array) | ||
| .map(this.transform.bind(this)) | ||
| .map(this.process.bind(this)) | ||
@@ -32,7 +36,11 @@ .sort(function(a, b){ | ||
| transform: function(d){ | ||
| return d.toLowerCase(); | ||
| }, | ||
| process: function(d){ | ||
| return { | ||
| d: d, | ||
| totalScore: this.factors.reduce((score, factor) => { | ||
| return score + factor.score(this.query.toLowerCase(), d); | ||
| totalScore: this.factors.reduce(function(score, factor){ | ||
| return score + (factor.weight*factor.score(d)); | ||
| }, 0), | ||
@@ -44,3 +52,4 @@ }; | ||
| function wordScore(query, word){ | ||
| Rater.wordScore = function(word){ | ||
| var score = 0; | ||
@@ -51,5 +60,10 @@ var queryIndex = 0; | ||
| for(var i=0, l=word.length; i<l; i++){ | ||
| if(word[i]===query[queryIndex]){ | ||
| if(word[i]===this.query[queryIndex]){ | ||
| straightMatches++; | ||
| score+=straightMatches; | ||
| var weightForMatchPosition = 1/(Math.abs(queryIndex-i)+1); | ||
| score+=weightForMatchPosition; | ||
| queryIndex++; | ||
@@ -61,5 +75,9 @@ }else{ | ||
| return score; | ||
| } | ||
| }; | ||
| Rater.wordLength = function(word){ | ||
| return -word.length; | ||
| }; | ||
| if(module && module.exports){ | ||
@@ -66,0 +84,0 @@ module.exports = Rater; |
+1
-1
| { | ||
| "name": "rater", | ||
| "description": "Rate objects based on custom factors", | ||
| "version": "0.0.1", | ||
| "version": "0.0.2", | ||
| "author": "David Wu <david.wuu@gmail.com>", | ||
@@ -6,0 +6,0 @@ "license": "MIT", |
1607
26.14%64
23.08%