Skip to content

Commit

Permalink
✨ Add String.match function
Browse files Browse the repository at this point in the history
  • Loading branch information
TomokiMiyauci committed Jun 19, 2021
1 parent f6f2563 commit b3339a1
Show file tree
Hide file tree
Showing 4 changed files with 58 additions and 0 deletions.
2 changes: 2 additions & 0 deletions dev_deps.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
export { assertEquals } from "https://deno.land/std@0.97.0/testing/asserts.ts";
export { equal } from "https://deno.land/x/equal@v1.5.0/mod.ts";

export const assertEqualsType = <T, U extends T = T>(_actual?: U): void => {};
27 changes: 27 additions & 0 deletions string/match.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
import { curry } from "../deps.ts";

/**
* @internal
*/
const _match = (
matcher: string | RegExp,
val: string,
): RegExpMatchArray | null => val.match(matcher);

/**
* Matches a string with a regular expression, and returns an array containing the results of that search.
* @param matcher - `RegExp` a variable name or string literal containing the regular expression pattern and flags
* @param val - Any `String`
* @returns The result of `val.match(matcher)`
*
* @example
* ```ts
* match(/xyz/, 'vwxyz') // ['xyz']
* ```
*
* @beta
*/
const match = curry(_match);

export { _match, match };
28 changes: 28 additions & 0 deletions string/match_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// Copyright 2021-present the Core-fn authors. All rights reserved. MIT license.
import { assertEquals, equal } from "../dev_deps.ts";
import { _match } from "./match.ts";

Deno.test("match", () => {
const table: [string | RegExp, string, RegExpMatchArray | null][] = [
["", "", [""]],
["c", "abc", ["c"]],
["aaaa", "aa", null],
["abc", "abcdabc", ["abc"]],
[/a/, "bcd", null],
[/a/, "abc", ["a"]],
[/a(.*)/, "abc", ["abc", "bc"]],
[/a(?<name>.*)/, "abc", ["abc", "bc"]],
[/a/g, "abc", ["a"]],
[/a/g, "abaca", ["a", "a", "a"]],
];
table.forEach(([matcher, val, expected]) => {
assertEquals(
equal(
_match(matcher, val),
expected,
),
true,
`match(${matcher}, ${val}) -> ${expected}`,
);
});
});
1 change: 1 addition & 0 deletions string/mod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ export { toUpperCase } from "./to_upper_case.ts";
export { repeat } from "./repeat.ts";
export { trimEnd } from "./trim_end.ts";
export { trimStart } from "./trim_start.ts";
export { match } from "./match.ts";

0 comments on commit b3339a1

Please sign in to comment.