allow specifying multiple fields

This commit is contained in:
Timo Hocker 2020-06-26 16:11:30 +02:00
parent 0932891b20
commit 9f41d623e4
4 changed files with 64 additions and 3 deletions

2
Jenkinsfile vendored
View File

@ -5,7 +5,7 @@ pipeline {
VERSION = VersionNumber([ VERSION = VersionNumber([
versionNumberString: versionNumberString:
'${BUILDS_ALL_TIME}', '${BUILDS_ALL_TIME}',
versionPrefix: '1.4.', versionPrefix: '1.5.',
worstResultForIncrement: 'SUCCESS' worstResultForIncrement: 'SUCCESS'
]) ])
} }

View File

@ -1,6 +1,6 @@
# @sapphirecode/utilities # @sapphirecode/utilities
version: 1.4.x version: 1.5.x
small utility functions to make much needed features easier to work with small utility functions to make much needed features easier to work with
@ -110,6 +110,21 @@ console.log(JSON.stringify(result, null, 2));
]*/ ]*/
``` ```
filters can also apply to multiple fields
```js
const result = util.recursive_filter(
[{name: 'foo', name_2: 'bar'}],
[
{
filter: /foo bar/iu,
fields: ['name', 'name_2'] // fields will be joined with a space in between
// {name: 'foo', name_2: 'bar'} will become 'foo bar'
}
]
);
```
## License ## License
MIT © Timo Hocker <timo@scode.ovh> MIT © Timo Hocker <timo@scode.ovh>

View File

@ -91,7 +91,17 @@ function recursive_filter (input, filters, children_key = 'children') {
for (const e of data) { for (const e of data) {
let match = true; let match = true;
for (const filter of filters) { for (const filter of filters) {
if (!filter.filter.test (e[filter.field])) { let search_str = '';
if (
typeof filter.fields !== 'undefined'
&& Array.isArray (filter.fields)
) {
search_str = filter.fields.map ((f) => e[f])
.join (' ');
}
else { search_str = e[filter.field]; }
if (!filter.filter.test (search_str)) {
match = false; match = false;
break; break;
} }

View File

@ -147,3 +147,39 @@ test ('recursive filter', (t) => {
const result = util.recursive_filter (raw, [ filter ]); const result = util.recursive_filter (raw, [ filter ]);
t.deepEqual (filtered, result); t.deepEqual (filtered, result);
}); });
test ('recursive filter multifield', (t) => {
const raw = [
{ name: 'foo', f: 'include' },
{
name: 'include_bar',
children: [
{ name: 'foo' },
{ name: 'bar' }
]
},
{
name: 'baz',
children: [
{ name: 'include_foo' },
{ name: 'bar' }
]
},
{
name: 'barbaz',
children: [
{ name: 'foo' },
{ name: 'bar' }
]
}
];
const filtered = [
{ name: 'foo', f: 'include' }
];
const filter = {
fields: ['name', 'f'],
filter: /foo include/ui
};
const result = util.recursive_filter (raw, [ filter ]);
t.deepEqual (filtered, result);
});