Skip to content

Commit 7f1e836

Browse files
committed
Implement unique value filtering in parseArray function and add corresponding tests. Updated function signature to accept an options object for separator and uniqueValues. Enhanced filtering logic to support duplicate removal based on the uniqueValues option.
1 parent 3f332a2 commit 7f1e836

2 files changed

Lines changed: 39 additions & 4 deletions

File tree

src/helpers/parseArray.test.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,4 +17,28 @@ describe("parseArray", () => {
1717
expect(parseArray("a|b|c", { separator: "|" })).toEqual(["a", "b", "c"]);
1818
expect(parseArray("x; y ;z", { separator: ";" })).toEqual(["x", "y", "z"]);
1919
});
20+
21+
test("uniqueValues removes duplicates", () => {
22+
expect(
23+
parseArray("a,b;a;c;b,a", { separator: ";", uniqueValues: true })
24+
).toEqual(["a,b", "a", "c", "b,a"]);
25+
expect(parseArray("a,b,a,c,b", { uniqueValues: true })).toEqual([
26+
"a",
27+
"b",
28+
"c",
29+
]);
30+
});
31+
32+
test("uniqueValues keeps duplicates when false", () => {
33+
expect(parseArray("a,b,a,c,b")).toEqual(["a", "b", "a", "c", "b"]);
34+
expect(parseArray("a,b,a", { uniqueValues: false })).toEqual([
35+
"a",
36+
"b",
37+
"a",
38+
]);
39+
});
40+
41+
test("uniqueValues with numeric-like values", () => {
42+
expect(parseArray("1,2,1,3", { uniqueValues: true })).toEqual([1, 2, 3]);
43+
});
2044
});

src/helpers/parseArray.ts

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isEmptyString } from "../validators";
12
import { ParsedPrimitive, parsePrimitive } from "./parsePrimitive";
23

34
/**
@@ -8,12 +9,22 @@ import { ParsedPrimitive, parsePrimitive } from "./parsePrimitive";
89
*/
910
export const parseArray = (
1011
str: string,
11-
options?: { separator?: string }
12+
{
13+
separator = ",",
14+
uniqueValues = false,
15+
}: { separator?: string; uniqueValues?: boolean } = {}
1216
): ParsedPrimitive[] => {
13-
const { separator = "," } = options ?? {};
14-
1517
return str
1618
.split(separator)
1719
.map((v) => parsePrimitive(v))
18-
.filter(Boolean);
20+
.filter((v, index, self) => {
21+
// Keep 0, null, undefined etc. but not empty strings
22+
if (isEmptyString(v as string)) {
23+
return false;
24+
}
25+
if (uniqueValues) {
26+
return self.indexOf(v) === index; // keep it simple, don't use Set
27+
}
28+
return true;
29+
});
1930
};

0 commit comments

Comments
 (0)