From 0dab4976ae6cf7353fe6762a686b73305eecadb4 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Fri, 3 Jul 2020 14:36:39 +0200 Subject: [PATCH] allow custom functions in filters --- Jenkinsfile | 2 +- README.md | 12 +++++++++++- index.js | 3 +++ test/index.js | 27 +++++++++++++++++++++++++++ 4 files changed, 42 insertions(+), 2 deletions(-) diff --git a/Jenkinsfile b/Jenkinsfile index 8c0fcda..b13c91f 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -5,7 +5,7 @@ pipeline { VERSION = VersionNumber([ versionNumberString: '${BUILDS_ALL_TIME}', - versionPrefix: '1.7.', + versionPrefix: '1.8.', worstResultForIncrement: 'SUCCESS' ]) } diff --git a/README.md b/README.md index a884a62..3ae2e1e 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # @sapphirecode/utilities -version: 1.7.x +version: 1.8.x small utility functions to make much needed features easier to work with @@ -178,6 +178,16 @@ field values can be carried to filter runs on children to filter over the entire */ ``` +custom functions to match items can also be used + +```js +const filter = { + function: (element) => { + return element.should_match; + } +} +``` + ## License MIT © Timo Hocker diff --git a/index.js b/index.js index 685d433..662ee59 100644 --- a/index.js +++ b/index.js @@ -85,6 +85,9 @@ function get_element_field (element, carried_data, field) { } function check_filter (filter, e, carried_data) { + if (typeof filter.function !== 'undefined') + return filter.function ({ ...e, ...carried_data }); + const search_str = Array.isArray (filter.field) ? filter.field.map ((f) => get_element_field (e, carried_data, f)) .filter ((v) => typeof v !== 'undefined') diff --git a/test/index.js b/test/index.js index 5614d7c..900a8b5 100644 --- a/test/index.js +++ b/test/index.js @@ -252,3 +252,30 @@ test ('recursive filter carry field', (t) => { } ]); }); + +test ('recursive filter custom function', (t) => { + const to_filter = [ + { + name: 'foo', + children: [ + { name: 'bar' }, + { name: 'baz' }, + { foo: 'bar' } + ] + } + ]; + + const res = util.recursive_filter ( + to_filter, + [ { function: (elem) => elem.name === 'foo bar' } ], + 'children', + [ 'name' ] + ); + + t.deepEqual (res, [ + { + name: 'foo', + children: [ { name: 'bar' } ] + } + ]); +});