Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: ensure inline rules merged are collections (#237)
- Loading branch information
Showing
5 changed files
with
56 additions
and
53 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
'use strict' | ||
|
||
const { | ||
cloneDeep, | ||
concat, | ||
first, | ||
findIndex, | ||
forEach, | ||
chain, | ||
castArray, | ||
has, | ||
set | ||
} = require('lodash') | ||
|
||
const forEachRule = (collection, fn) => forEach(castArray(collection), fn) | ||
|
||
const loadRules = rulesBundle => | ||
chain(rulesBundle) | ||
.reduce((acc, { test, ...rules }) => { | ||
forEach(rules, (innerRules, propName) => { | ||
if (test) forEachRule(innerRules, rule => (rule.test = test)) | ||
|
||
set( | ||
acc, | ||
propName, | ||
has(acc, propName) | ||
? concat(acc[propName], innerRules) | ||
: concat(innerRules) | ||
) | ||
|
||
return acc | ||
}) | ||
return acc | ||
}, {}) | ||
.toPairs() | ||
.value() | ||
|
||
const mergeRules = (rules, baseRules) => | ||
chain(rules) | ||
.reduce((acc, { test, ...rules }) => { | ||
forEach(rules, (innerRules, propName) => { | ||
if (test) forEachRule(innerRules, rule => (rule.test = test)) | ||
// find the rules associated with `propName` | ||
const index = findIndex(acc, item => first(item) === propName) | ||
// if `propName` has more rule, add the new rule from the end | ||
if (index !== -1) acc[index][1] = concat(innerRules, ...acc[index][1]) | ||
// otherwise, create an array of rules | ||
else acc.push([propName, castArray(innerRules)]) | ||
}) | ||
return acc | ||
}, cloneDeep(baseRules)) | ||
.value() | ||
|
||
module.exports = { mergeRules, loadRules } |