[ui/fieldWildcard] add lib to match names based on field-style wildcards

This commit is contained in:
spalger 2016-04-05 01:02:01 -07:00 committed by Stéphane Campinas
parent d4b9c116a6
commit d75a63fa34
2 changed files with 76 additions and 0 deletions

View file

@ -0,0 +1,65 @@
import expect from 'expect.js';
import { makeRegEx, fieldWildcardFilter } from '../field_wildcard';
describe('fieldWildcard', function () {
describe('makeRegEx', function () {
it('matches * in any position', function () {
expect('aaaaaabbbbbbbcccccc').to.match(makeRegEx('*a*b*c*'));
expect('a1234').to.match(makeRegEx('*1234'));
expect('1234a').to.match(makeRegEx('1234*'));
expect('12a34').to.match(makeRegEx('12a34'));
});
});
describe('filter', function () {
it('filters nothing when given an empty array', function () {
const filter = fieldWildcardFilter([]);
const original = [
'foo',
'bar',
'baz',
1234
];
expect(original.filter(filter)).to.eql(original);
});
it('filters values that match the globs', function () {
const filter = fieldWildcardFilter([
'f*',
'*4'
]);
const original = [
'foo',
'bar',
'baz',
1234
];
expect(original.filter(filter)).to.eql(['bar', 'baz']);
});
it('handles weird values okay', function () {
const filter = fieldWildcardFilter([
'f*',
'*4',
'undefined'
]);
const original = [
'foo',
null,
'bar',
undefined,
{},
[],
'baz',
1234
];
expect(original.filter(filter)).to.eql([null, 'bar', {}, [], 'baz']);
});
});
});

View file

@ -0,0 +1,11 @@
import { memoize } from 'lodash';
export const makeRegEx = memoize(function makeRegEx(glob) {
return new RegExp(glob.replace(/\*/g, '.*'));
});
export function fieldWildcardFilter(globs) {
return function filter(val) {
return !globs.some(p => makeRegEx(p).test(val));
};
}