Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 11 additions & 5 deletions src/match-pattern.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,16 +36,22 @@ export function match<T, U = never>(value: any, patterns: MatchPatterns<T, U>):
} else if (isNone(value) && patterns.None !== undefined) {
return patterns.None as T;
}

for (const p in patterns) {

if (p === "Some" || p === "None") continue;

const patternKey = String(p);
const isRange = patternKey.includes("..=");
const isOr = patternKey.includes("|");
const isRegex = patternKey.startsWith("/") && patternKey.endsWith("/");


const lastSlashIndex = patternKey.lastIndexOf("/");
const foundFlags = patternKey.slice(lastSlashIndex + 1).split("");

const isRegex = !!foundFlags.length
? patternKey.startsWith("/") && [ 'g', 'i', 'm', 'u', 's', 'y' ].some((flag) => foundFlags.includes(flag))
: patternKey.startsWith("/") && patternKey.endsWith("/");

if (isRange) {
const [start, end] = patternKey.split("..=").map(s => isNaN(Number(s)) ? s : Number(s));

Expand All @@ -55,12 +61,12 @@ export function match<T, U = never>(value: any, patterns: MatchPatterns<T, U>):
}
} else if (isOr) {
const patternValues = patternKey.split("|").map(s => isNaN(Number(s)) ? s : Number(s));

if (patternValues.includes(value)) {
return patterns[p]();
}
} else if (isRegex) {
const regex = new RegExp(patternKey.slice(1, -1));
const regex = new RegExp(patternKey.slice(1, lastSlashIndex), foundFlags.join(""));

if (regex.test(value)) {
return patterns[p]();
Expand Down
4 changes: 3 additions & 1 deletion tests/match-pattern.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ describe('testing match pattern function', () => {
"1..=13": () => "Between 1 and 13",
"25 | 50 | 100": () => "A bill",
"/[a-z]/": () => "A lowercase letter",
"/boost/i": () => "case ignored",
"_": () => "default",
};

Expand All @@ -34,6 +35,7 @@ describe('testing match pattern function', () => {
expect(match(10, matchValidates)).toBe("Between 1 and 13");
expect(match(25, matchValidates)).toBe("A bill");
expect(match("z", matchValidates)).toBe("A lowercase letter");
expect(match("BOOST", matchValidates)).toBe("case ignored");
expect(match("1", matchValidates)).toBe("default");
});

Expand All @@ -45,4 +47,4 @@ describe('testing match pattern function', () => {
[Coin.Quarter]: () => 25,
})).toBe(10);
});
});
});