Skip to content

Commit 642b5ba

Browse files
committed
✨ Add title oparating functions
1 parent bd8b8a8 commit 642b5ba

File tree

3 files changed

+82
-0
lines changed

3 files changed

+82
-0
lines changed

deps/testing.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export * from "https://deno.land/[email protected]/testing/asserts.ts";

title.test.ts

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import { encodeTitleURI, revertTitleLc, toTitleLc } from "./title.ts";
2+
import { assertStrictEquals } from "./deps/testing.ts";
3+
4+
Deno.test("toTitleLc()", async (t) => {
5+
await t.step("` ` -> `_`", () => {
6+
assertStrictEquals<string>(toTitleLc("空白入り タイトル"), "空白入り_タイトル");
7+
assertStrictEquals<string>(
8+
toTitleLc(" 前後にも 空白入り _タイトル "),
9+
"_前後にも_空白入り__タイトル_",
10+
);
11+
});
12+
13+
await t.step("upper -> lower", () => {
14+
assertStrictEquals<string>(toTitleLc("Scrapbox-Gyazo"), "scrapbox-gyazo");
15+
assertStrictEquals<string>(
16+
toTitleLc("全角アルファベット「Scrapbox」も変換できる"),
17+
"全角アルファベット「scrapbox」も変換できる",
18+
);
19+
});
20+
await t.step("UPPER Case -> lower_case", () => {
21+
assertStrictEquals<string>(
22+
toTitleLc("Scrapbox is one of the products powered by Nota inc."),
23+
"scrapbox_is_one_of_the_products_powered_by_nota_inc.",
24+
);
25+
});
26+
});
27+
28+
Deno.test("revertTitleLc()", () => {
29+
assertStrictEquals<string>(
30+
revertTitleLc("Title_with underscore"),
31+
"Title with underscore",
32+
);
33+
});
34+
35+
Deno.test("encodeTitleURI()", async (t) => {
36+
await t.step("tail symbol", () => {
37+
assertStrictEquals<string>(encodeTitleURI(":title:"), ":title%3A");
38+
});
39+
});

title.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
/** 文字列をtitleLc形式に変換する
2+
*
3+
* - ` ` -> `_`
4+
*
5+
* - 大文字 -> 小文字
6+
*
7+
* リンクの等値比較をする際に主に使われる
8+
*
9+
* @param text 変換する文字列
10+
* @return 変換後の文字列
11+
*/
12+
export const toTitleLc = (text: string): string =>
13+
text.replaceAll(" ", "_").toLowerCase();
14+
15+
/** `_`を半角スペースに変換する
16+
*
17+
* @param text 変換する文字列
18+
* @return 変換後の文字列
19+
*/
20+
export const revertTitleLc = (text: string): string =>
21+
text.replaceAll("_", " ");
22+
23+
/** titleをURIで使える形式にEncodeする
24+
*
25+
* @param title 変換するtitle
26+
* @return 変換後の文字列
27+
*/
28+
export const encodeTitleURI = (title: string): string => {
29+
return [...title].map((char, index) => {
30+
if (char === " ") return "_";
31+
if (
32+
!noEncodeChars.includes(char) ||
33+
(index === title.length - 1 && noTailChars.includes(char))
34+
) {
35+
return encodeURIComponent(char);
36+
}
37+
return char;
38+
}).join("");
39+
};
40+
41+
const noEncodeChars = '@$&+=:;",';
42+
const noTailChars = ':;",';

0 commit comments

Comments
 (0)