Skip to content

Commit

Permalink
Refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
ehmicky committed Mar 13, 2022
1 parent 9adf503 commit 84bfafa
Showing 1 changed file with 31 additions and 11 deletions.
42 changes: 31 additions & 11 deletions src/config/normalize/lib/wild_wild_path/iterate/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,26 +10,36 @@ import { expandToken } from './expand.js'
// Uses an iterator:
// - To allow consumers to return only the first matching entry quickly
// - To keep memory consumption low even on big queries
export const iterate = function* (target, query, { childFirst = false } = {}) {
export const iterate = function* (
target,
query,
{ childFirst = false, sort = false } = {},
) {
const queryArrays = parseQuery(query)
const entries = queryArrays.map((queryArray) => ({
queryArray,
value: target,
path: [],
missing: false,
}))
yield* iterateLevel(entries, childFirst, 0)
yield* iterateLevel({ entries, childFirst, sort, index: 0 })
}

const iterateLevel = function* (entries, childFirst, index) {
const iterateLevel = function* ({ entries, childFirst, sort, index }) {
const entriesA = removeDuplicates(entries)
const parentEntries = getParentEntries(entriesA, index)

if (!childFirst) {
yield* parentEntries
}

yield* iterateChildEntries(entries, parentEntries, childFirst, index)
yield* iterateChildEntries({
entries,
parentEntries,
childFirst,
sort,
index,
})

if (childFirst) {
yield* parentEntries
Expand All @@ -47,13 +57,13 @@ const normalizeEntry = function ({ value, path, missing }) {
return { value, path, query, missing }
}

// eslint-disable-next-line max-params
const iterateChildEntries = function* (
const iterateChildEntries = function* ({
entries,
parentEntries,
childFirst,
sort,
index,
) {
}) {
if (parentEntries.length === entries.length) {
return
}
Expand All @@ -66,22 +76,32 @@ const iterateChildEntries = function* (
return
}

yield* iterateChildren(childEntries, childFirst, index)
yield* iterateChildren({ childEntries, childFirst, sort, index })
}

const iterateChildren = function* (childEntries, childFirst, index) {
const iterateChildren = function* ({ childEntries, childFirst, sort, index }) {
const nextIndex = index + 1

if (childEntries.length === 1) {
yield* iterateLevel(childEntries, childFirst, nextIndex)
yield* iterateLevel({
entries: childEntries,
childFirst,
sort,
index: nextIndex,
})
return
}

const childEntriesGroups = Object.values(groupBy(childEntries, getLastProp))

// eslint-disable-next-line fp/no-loops
for (const childEntriesA of childEntriesGroups) {
yield* iterateLevel(childEntriesA, childFirst, nextIndex)
yield* iterateLevel({
entries: childEntriesA,
childFirst,
sort,
index: nextIndex,
})
}
}

Expand Down

0 comments on commit 84bfafa

Please sign in to comment.