Skip to content

Commit

Permalink
Fix isParent()
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Jan 23, 2022
1 parent 263f137 commit 4f1de03
Showing 1 changed file with 25 additions and 6 deletions.
31 changes: 25 additions & 6 deletions src/config/normalize/lib/prop_path/compare.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,38 @@
import { parse } from './parse.js'

// Returns whether a query is a parent to another one, such as `a.b` and `a.b.c`
// Wildcards always match, i.e. `a.*` is a parent to `a.b.c` and
// `a.b` is a parent to `a.*.c`.
// Wildcards always match
// - `a.*` is a parent to `a.b.c`
// - `a.b` is a parent to `a.*.c`
// Since this is used to define sorting order, properties with only
// differing wildcard are parents to each other:
// - `*.b` is a parent to `a.*`
// - `a.*` is a parent to `a.b`
// A query is not a parent to itself, nor to a sibling.
export const isParent = function (childQuery, parentQuery) {
const childTokens = parse(childQuery)
const parentTokens = parse(parentQuery)
return (
parentTokens.length < childTokens.length &&
parentTokens.every((parentToken, index) =>
isSameToken(parentToken, childTokens[index]),
)
childTokens.length >= parentTokens.length &&
areSameTokens(parentTokens, childTokens) &&
(childTokens.length !== parentTokens.length ||
compareSameSizeQueries(parentTokens, childTokens))
)
}

const areSameTokens = function (parentTokens, childTokens) {
return parentTokens.every((parentToken, index) =>
isSameToken(parentToken, childTokens[index]),
)
}

const isSameToken = function (tokenA, tokenB) {
return tokenA.wildcard || tokenB.wildcard || tokenA.key === tokenB.key
}

const compareSameSizeQueries = function (parentTokens, childTokens) {
const differentParentToken = parentTokens.find(
(parentToken, index) => parentToken.key !== childTokens[index].key,
)
return differentParentToken !== undefined && differentParentToken.wildcard
}

0 comments on commit 4f1de03

Please sign in to comment.