Skip to content

Instantly share code, notes, and snippets.

@reidev275
Last active August 29, 2015 13:56
Show Gist options
  • Save reidev275/9119156 to your computer and use it in GitHub Desktop.
Save reidev275/9119156 to your computer and use it in GitHub Desktop.
Simple javascript searching
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 || {});
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');
});
@jonkemp
Copy link

jonkemp commented Feb 20, 2014

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment