Last active
August 29, 2015 13:56
-
-
Save reidev275/9119156 to your computer and use it in GitHub Desktop.
Simple javascript searching
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
var MyNamespace = (function(namespace) { | |
if (!Array.prototype.filter) { | |
Array.prototype.filter = function(fun /*, thisp */) { | |
"use strict"; | |
if (this == null) throw new TypeError(); | |
var t = Object(this); | |
var len = t.length >>> 0; | |
if (typeof fun != "function") throw new TypeError(); | |
var res = []; | |
var thisp = arguments[1]; | |
for (var i = 0; i < len; i++) { | |
if (i in t) { | |
var val = t[i]; // in case fun mutates this | |
if (fun.call(thisp, val, i, t)) res.push(val); | |
} | |
} | |
return res; | |
}; | |
} | |
namespace.search = function(arr, query, field) { | |
var re = new RegExp(query, 'i'); | |
return arr.filter(function(item) { | |
if (field) | |
return re.test(item[field]); | |
else | |
return re.test(item); | |
}); | |
}; | |
return namespace; | |
})(MyNamespace || {}); |
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
test( "simple array test", function() { | |
var simpleArray = ['audi', 'acura', 'buick']; | |
var result = MyNamespace.search(simpleArray, 'a'); | |
ok( result[0] == 'audi' && | |
result[1] == 'acura'); | |
}); | |
test( "collection test", function() { | |
var collection = [ | |
{ make: 'audi', model: 'a4' }, | |
{ make: 'acura', model: 'TL' }, | |
{ make: 'buick', model: 'Skylark' }]; | |
var result = MyNamespace.search(collection, 'a', 'make'); | |
ok( result[0] == 'audi' && | |
result[1] == 'acura'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't have to write this.
if (typeof field != 'undefined')
You can just write this instead.
if (field)
I would also run it through a linter, like JSHint.
Everything else looks ok to me.