Skip to content

Commit c515552

Browse files
committed
✨ Enable to calculate the number of indent
1 parent 448d044 commit c515552

File tree

3 files changed

+48
-0
lines changed

3 files changed

+48
-0
lines changed

is.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
// These code are based on https://deno.land/x/unknownutil@v1.1.0/is.ts
2+
3+
export const isNone = (value: unknown): value is undefined | null =>
4+
value === null || value === undefined;
5+
export const isString = (value: unknown): value is string =>
6+
typeof value === "string";
7+
export const isNumber = (value: unknown): value is number =>
8+
typeof value === "number";
9+
export const isArray = <T>(value: unknown): value is T[] =>
10+
Array.isArray(value);

text.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { getIndentCount } from "./text.ts";
2+
import { assertStrictEquals } from "./deps/testing.ts";
3+
4+
Deno.test("getIndentCount()", () => {
5+
assertStrictEquals(getIndentCount("sample text "), 0);
6+
assertStrictEquals(getIndentCount(" sample text "), 2);
7+
assertStrictEquals(getIndentCount("   sample text"), 3);
8+
assertStrictEquals(getIndentCount("\t \t  sample text"), 5);
9+
});

text.ts

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { isString } from "./is.ts";
2+
3+
export const getIndentCount = (text: string): number =>
4+
text.match(/^(\s*)/)?.[1]?.length ?? 0;
5+
6+
/** 指定した行の配下にある行の数を返す
7+
*
8+
* @param index 指定したい行の行番号
9+
* @param lines 行のリスト
10+
*/
11+
export function getIndentLineCount(
12+
index: number,
13+
lines: string[] | { text: string }[],
14+
): number {
15+
const base = getIndentCount(getText(index, lines));
16+
let count = 0;
17+
while (
18+
index + count + 1 < lines.length &&
19+
(getIndentCount(getText(index + count + 1, lines))) > base
20+
) {
21+
count++;
22+
}
23+
return count;
24+
}
25+
26+
function getText(index: number, lines: string[] | { text: string }[]) {
27+
const line = lines[index];
28+
return isString(line) ? line : line.text;
29+
}

0 commit comments

Comments
 (0)