Update Filter utility functions

- Write simple tests for multi_test
- Add get_attr_caseless function for improving Filter.Match
This commit is contained in:
Patrick Mooney 2013-11-30 23:31:15 -06:00
parent dfbb6031c6
commit 57fecb06d5
2 changed files with 81 additions and 0 deletions

View File

@ -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;
};

View File

@ -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();
});