diff --git a/lib/filters/filter.js b/lib/filters/filter.js index 4ebc39b..c27a4ac 100644 --- a/lib/filters/filter.js +++ b/lib/filters/filter.js @@ -73,3 +73,22 @@ Filter.multi_test = function (rule, value) { return rule(value); } }; + +// Search object for attribute, insensitive to case +Filter.get_attr_caseless = function (target, attr) { + // Check for exact case match first + if (target.hasOwnProperty(attr)) { + return target[attr]; + } + // Perform case-insensitive enumeration after that + var lower = attr.toLowerCase(); + var result = null; + Object.getOwnPropertyNames(target).some(function (item) { + if (item.toLowerCase() == lower) { + result = target[item]; + return true; + } + return false; + }); + return result; +}; diff --git a/test/filters/filter.test.js b/test/filters/filter.test.js new file mode 100644 index 0000000..9d17224 --- /dev/null +++ b/test/filters/filter.test.js @@ -0,0 +1,62 @@ +// Copyright 2011 Mark Cavage, Inc. All rights reserved. + +var test = require('tap').test; + + +///--- Globals + +var Filter; + + +///--- Tests + +test('load library', function (t) { + var filters = require('../../lib/index').filters; + t.ok(filters); + Filter = filters.Filter; + t.ok(Filter); + t.end(); +}); + + +test('multi_test array', function (t) { + var rule = function (item) { + return (item == 3); + }; + t.ok(Filter.multi_test(rule, [1, 2, 3])); + t.ok(!Filter.multi_test(rule, [1, 2])); + t.end(); +}); + + +test('multi_test value', function (t) { + var rule = function (item) { + return (item == 3); + }; + t.ok(Filter.multi_test(rule, 3)); + t.ok(!Filter.multi_test(rule, 1)); + t.end(); +}); + + +test('get_attr_caseless exact match', function (t) { + var f = Filter.get_attr_caseless; + t.equal(f({attr: 'testval'}, 'attr'), 'testval'); + t.equal(f({attr: 'testval'}, 'missing'), null); + t.end(); +}); + + +test('get_attr_caseless insensitive match', function (t) { + var f = Filter.get_attr_caseless; + var data = { + lower: 'lower', + UPPER: 'upper', + MiXeD: 'mixed' + }; + t.equal(f(data, 'lower'), 'lower'); + t.equal(f(data, 'upper'), 'upper'); + t.equal(f(data, 'mixed'), 'mixed'); + t.equal(f(data, 'missing'), null); + t.end(); +});