Skip to content

Commit

Permalink
add getDuplicatesOf array util to @ark/util, bumping the package vers…
Browse files Browse the repository at this point in the history
…ion from 0.23.0 to 0.24.0
  • Loading branch information
TizzySaurus committed Nov 17, 2024
1 parent 624c0ac commit 9826c00
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
28 changes: 28 additions & 0 deletions ark/util/arrays.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,34 @@ import type { anyOrNever, conform } from "./generics.ts"
import type { isDisjoint } from "./intersections.ts"
import type { parseNonNegativeInteger } from "./numbers.ts"

type DuplicateData<val = unknown> = { element: val; indices: number[] }

/**
* Extracts duplicated elements and their indices from an array, returning them.
*
* @param arr The array to extract duplicate elements from.
*/ export const getDuplicatesOf = <const arr extends array>(
arr: arr,
opts?: ComparisonOptions<arr[number]>
): DuplicateData<arr[number]>[] => {
const isEqual = opts?.isEqual ?? ((l, r) => l === r)

const seenElements: Set<arr[number]> = new Set()
const duplicates: DuplicateData<arr[number]>[] = []

arr.forEach((element, indx) => {
if (seenElements.has(element)) {
const duplicatesEntryIndx = duplicates.findIndex((l, r) =>
isEqual(l.element, r)
)
if (duplicatesEntryIndx === -1)
duplicates.push({ element, indices: [indx] })
else duplicates[duplicatesEntryIndx].indices.push(indx)
} else seenElements.add(element)
})
return duplicates
}

export type pathToString<
segments extends string[],
delimiter extends string = "/"
Expand Down
2 changes: 1 addition & 1 deletion ark/util/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@ark/util",
"version": "0.23.0",
"version": "0.24.0",
"license": "MIT",
"author": {
"name": "David Blass",
Expand Down

0 comments on commit 9826c00

Please sign in to comment.