diff --git a/lib/fuzzy.js b/lib/fuzzy.js index 83cf4fe..f7de08a 100644 --- a/lib/fuzzy.js +++ b/lib/fuzzy.js @@ -48,7 +48,9 @@ fuzzy.match = function(pattern, str, opts) { // String to compare against. This might be a lowercase version of the // raw string , compareString = opts.caseSensitive && str || str.toLowerCase() - , ch; + , ch + , matchIndices = [] + ; pattern = opts.caseSensitive && pattern || pattern.toLowerCase(); @@ -62,6 +64,7 @@ fuzzy.match = function(pattern, str, opts) { // consecutive characters should increase the score more than linearly currScore += 1 + currScore; + matchIndices.push(idx); } else { currScore = 0; } @@ -73,7 +76,7 @@ fuzzy.match = function(pattern, str, opts) { if(patternIdx === pattern.length) { // if the string is an exact match with pattern, totalScore should be maxed totalScore = (compareString === pattern) ? Infinity : totalScore; - return {rendered: result.join(''), score: totalScore}; + return {rendered: result.join(''), score: totalScore, indices: matchIndices}; } return null; @@ -86,6 +89,7 @@ fuzzy.match = function(pattern, str, opts) { // string: 'lah' // The rendered string // , index: 2 // The index of the element in `arr` // , original: 'blah' // The original element in `arr` +// , indices: [0] // }] // // `opts` is an optional argument bag. Details: @@ -124,6 +128,7 @@ fuzzy.filter = function(pattern, arr, opts) { , score: rendered.score , index: idx , original: element + , indices: rendered.indices }; } return prev; @@ -141,4 +146,3 @@ fuzzy.filter = function(pattern, arr, opts) { }()); - diff --git a/test/fuzzy.test.js b/test/fuzzy.test.js index 81b39d3..fe9e67f 100644 --- a/test/fuzzy.test.js +++ b/test/fuzzy.test.js @@ -48,6 +48,9 @@ describe('fuzzy', function(){ opts.caseSensitive = false; expect(fuzzy.match('AB', 'AB', opts)).to.not.equal(null); }); + it('should return indices of matching characters', function (){ + expect(fuzzy.match('bd','abcde').indices).to.deep.equal([1,3]); + }) xit('should return the same score for matches in the middle as matches at beginning', function(){ // TODO: Dont know how I feel about this. Sublime weights characters that // appear toward the beginning of the string a bit higher @@ -86,11 +89,13 @@ describe('fuzzy', function(){ expect(result[0].string).to.equal('aba'); expect(result[0].index).to.equal(0); expect(result[0]).to.have.property('score'); + expect(result[0].indices).to.deep.equal([0,1]); // verify second result expect(result[1].string).to.equal('cacb'); expect(result[1].index).to.equal(2); expect(result[1]).to.have.property('score'); + expect(result[1].indices).to.deep.equal([1,3]); }); it('should use optional template stringing to wrap each element', function(){ var rendered = fuzzy.filter('a', ['a'], {