Skip to content

Commit

Permalink
refactor: update array.search to return the same structure of the sea…
Browse files Browse the repository at this point in the history
…rched array
  • Loading branch information
jorenrui committed Mar 24, 2024
1 parent 545a465 commit 9948bce
Showing 1 changed file with 30 additions and 12 deletions.
42 changes: 30 additions & 12 deletions lib/helpers/array.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,31 @@ function deepSubtract(arr, values) {
return newArray
}

function deepSearch(arr, queries, isSubItem = false) {
const newArray = []

for (let i = 0; i < arr.length; i++) {
if (Array.isArray(arr[i])) {
const subArray = deepSearch(arr[i], queries, true)

if (subArray.length > 0)
newArray.push(subArray)
} else {
const lowercaseItem = arr[i].toString().trim().toLowerCase()
const matches = queries.some((query) => lowercaseItem.includes(query))

if (matches) {
if (isSubItem)
return arr
else
newArray.push(arr[i])
}
}
}

return newArray
}

function flattenArgs(args) {
return args
.map((arg) => (Array.isArray(arg) ? arg.flat(Infinity) : [arg]))
Expand Down Expand Up @@ -135,20 +160,13 @@ export class MiniArray extends Array {
search(...args) {
const queries = args
.map((arg) =>
(Array.isArray(arg) ? arg.flat(Infinity) : [arg]).map((query) =>
query.toString().trim().toLowerCase().split(/\s+/)
)
)
.flat()

const matches = this.deepFlat().filter((item) => {
const lowercaseItem = item.toString().trim().toLowerCase()
return queries.some((query) =>
query.every((world) => lowercaseItem.includes(world))
(Array.isArray(arg) ? arg.flat(Infinity) : [arg]).map((query) => {
return query.toString().trim().toLowerCase().split()
})
)
})
.flat(Infinity)

return new MiniArray(...matches)
return new MiniArray(...deepSearch(this, queries))
}

sameAs(array) {
Expand Down

0 comments on commit 9948bce

Please sign in to comment.