marclundgren
12/10/2014 - 10:44 PM

fuzzy.js

/* jshint strict:false, asi:true */

var fuzzy = function(items, key) {
  return function(query) {
    var words  = query.toLowerCase().split(' ');

    return items.filter(function(item) {
      var normalizedTerm = item[key].toLowerCase();

      return words.every(function(word) {
        return (normalizedTerm.indexOf(word) > -1);
      });
    });
  };
};

var articles = [{
  title: '2014 Javascript MVC Frameworks Comparison',
  author: 'Guybrush Treepwood'
}, {
  title: 'Javascript in the year 2014',
  author: 'Herman Toothrot'
},
{
  title: 'Javascript in the year 2013',
  author: 'Rapp Scallion'
}];

var searchByTitle = fuzzy(articles, 'title');

searchByTitle('javascript 2014')
// returns the 1st and 2nd items