-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
25 additions
and
6 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
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 | ||
} |