diff --git a/README.md b/README.md index 7285303..df72118 100644 --- a/README.md +++ b/README.md @@ -159,7 +159,8 @@ const filter = { const result = util.recursive_filter( to_filter, [filter], - 'children' + 'children', + true // let the function know, that it is running on an indexed object ); ``` diff --git a/index.js b/index.js index 21c47d5..583080c 100644 --- a/index.js +++ b/index.js @@ -92,9 +92,15 @@ function to_search_string (element, field) { * @param {Array} input * @param {Array<{field: string|string[], filter: RegExp}>} filters * @param {string} children_key field where children are stored + * @param {boolean} indexed set to true if the object was indexed * @returns {Array} filtered data */ -function recursive_filter (input, filters, children_key = 'children') { +function recursive_filter ( + input, + filters, + children_key = 'children', + indexed = false +) { const data = [ ...input ]; const filtered = []; for (let i = 0; i < data.length; i++) { @@ -109,16 +115,20 @@ function recursive_filter (input, filters, children_key = 'children') { break; } } - if (match) { + if (match && !indexed) { filtered.push (e); } else { - if (typeof e[children_key] === 'undefined') + if (!Array.isArray (e[children_key])) { + if (match && indexed) + filtered.push (e); continue; + } e[children_key] = recursive_filter ( e[children_key], filters, - children_key + children_key, + indexed ); if (e[children_key].length > 0) filtered.push (e); @@ -150,7 +160,10 @@ function filter_index ( .filter ((v) => typeof v !== 'undefined') .join (' '); } - search_str += to_search_string (e, field); + const self_str = to_search_string (e, field); + if (search_str.length > 0 && self_str.length > 0) + search_str += ' '; + search_str += self_str; e[index_field] = search_str; } } diff --git a/test/index.js b/test/index.js index ba5ae97..2696f72 100644 --- a/test/index.js +++ b/test/index.js @@ -205,6 +205,7 @@ test ('recursive filter undefined multifield', (t) => { t.deepEqual (res, []); }); +// eslint-disable-next-line max-lines-per-function test ('recursive filter multifield index', (t) => { const raw = [ { name: 'foo', f: 'include' }, @@ -218,7 +219,7 @@ test ('recursive filter multifield index', (t) => { { name: 'baz', children: [ - { name: 'include_foo' }, + { name: 'include_foo', f: 'include' }, { name: 'bar' } ] }, @@ -236,7 +237,19 @@ test ('recursive filter multifield index', (t) => { name: 'foo', f: 'include', search_index: 'foo include' + }, + { + name: 'baz', + children: [ + { + name: 'include_foo', + f: 'include', + search_index: 'include_foo include' + } + ], + search_index: 'include_foo include bar baz' } + ]; util.filter_index (raw, [ @@ -248,6 +261,6 @@ test ('recursive filter multifield index', (t) => { field: 'search_index', filter: /foo include/ui }; - const result = util.recursive_filter (raw, [ filter ]); + const result = util.recursive_filter (raw, [ filter ], 'children', true); t.deepEqual (filtered, result); });