Skip to content

Commit c1e5e3a

Browse files
committed
reorganize misc items
1 parent 83df1d7 commit c1e5e3a

File tree

9 files changed

+84
-92
lines changed

9 files changed

+84
-92
lines changed

src/local_storage.ts

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import { Lazy } from "./cache.ts";
2+
3+
export const checkLocalStorage = lazy(() => {
4+
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
5+
try {
6+
const x = "__storage_test__";
7+
localStorage.setItem(x, x);
8+
localStorage.removeItem(x);
9+
return true;
10+
} catch (e) {
11+
return e instanceof DOMException &&
12+
e.name === "QuotaExceededError" &&
13+
// acknowledge QuotaExceededError only if there's something already stored
14+
localStorage &&
15+
localStorage.length !== 0;
16+
}
17+
});
18+
export function setIgnoreError(key: string, value: string): void {
19+
if (checkLocalStorage()) {
20+
try {
21+
localStorage.setItem(key, value);
22+
} catch (error) {
23+
if (
24+
!(error instanceof DOMException) || error.name !== "QuotaExceededError"
25+
) {
26+
throw error;
27+
}
28+
}
29+
}
30+
}
31+
function lazy<T>(fn: () => T): () => T {
32+
const cache = new Lazy(fn);
33+
return () => cache.getValue();
34+
}

src/main.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,22 +5,17 @@ import { asComment } from "../dictionary/misc.ts";
55
import PROJECT_DATA from "../project_data.json" with { type: "json" };
66
import { ArrayResultError } from "./array_result.ts";
77
import { loadCustomDictionary } from "./dictionary.ts";
8-
import {
9-
checkLocalStorage,
10-
extractErrorMessage,
11-
flattenError,
12-
NEWLINES,
13-
setIgnoreError,
14-
} from "./misc.ts";
8+
import { checkLocalStorage, setIgnoreError } from "./local_storage.ts";
9+
import { flattenError } from "./misc.ts";
1510
import { translate } from "./mod.ts";
1611
import { clearCache } from "./parser/cache.ts";
12+
import { settings } from "./settings.ts";
1713
import {
1814
loadFromElements,
1915
loadFromLocalStorage,
2016
resetElementsToCurrent,
2117
resetElementsToDefault,
2218
} from "./settings_frontend.ts";
23-
import { settings } from "./settings.ts";
2419

2520
const TRANSLATE_LABEL = "Translate";
2621
const TRANSLATE_LABEL_MULTILINE = "Translate (Ctrl + Enter)";
@@ -286,7 +281,7 @@ function main(): void {
286281
: DICTIONARY_ERROR_UNFIXABLE_MESSAGE;
287282
const errorListMessage = errors
288283
.map(extractErrorMessage)
289-
.map((message) => `\n- ${message.replaceAll(NEWLINES, "$& ")}`);
284+
.map((message) => `\n- ${message.replaceAll(/\r?\n/g, "$& ")}`);
290285
displayToCustomDictionary(asComment(`${message}${errorListMessage}`));
291286
// deno-lint-ignore no-console
292287
console.error(error);
@@ -298,6 +293,13 @@ function main(): void {
298293
}
299294
});
300295
}
296+
function extractErrorMessage(error: unknown): string {
297+
if (error instanceof Error) {
298+
return error.message;
299+
} else {
300+
return `${error}`;
301+
}
302+
}
301303
function errorsFixable(errors: ReadonlyArray<unknown>): boolean {
302304
return errors.length > 0 &&
303305
errors.every((error) => error instanceof ArrayResultError);

src/misc.ts

Lines changed: 0 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
import { distinctBy } from "@std/collections/distinct-by";
2-
import { escape } from "@std/regexp/escape";
3-
import { Lazy } from "./cache.ts";
4-
5-
export const NEWLINES = /\r?\n/g;
62

73
export function nullableAsArray<T>(value?: T): ReadonlyArray<NonNullable<T>> {
84
if (value == null) {
@@ -27,91 +23,18 @@ export function repeatArray<T>(element: T, count: number): ReadonlyArray<T> {
2723
export function repeatWithSpace(text: string, count: number): string {
2824
return repeatArray(text, count).join(" ");
2925
}
30-
export const checkLocalStorage = lazy(() => {
31-
// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API
32-
try {
33-
const x = "__storage_test__";
34-
localStorage.setItem(x, x);
35-
localStorage.removeItem(x);
36-
return true;
37-
} catch (e) {
38-
return e instanceof DOMException &&
39-
e.name === "QuotaExceededError" &&
40-
// acknowledge QuotaExceededError only if there's something already stored
41-
localStorage &&
42-
localStorage.length !== 0;
43-
}
44-
});
45-
export function setIgnoreError(key: string, value: string): void {
46-
if (checkLocalStorage()) {
47-
try {
48-
localStorage.setItem(key, value);
49-
} catch (error) {
50-
if (
51-
!(error instanceof DOMException) || error.name !== "QuotaExceededError"
52-
) {
53-
throw error;
54-
}
55-
}
56-
}
57-
}
58-
export function assertOk(response: Response): Response {
59-
if (!response.ok) {
60-
const { url, status, statusText } = response;
61-
throw new Error(
62-
`unable to fetch ${url} (${status} ${statusText})`,
63-
);
64-
} else {
65-
return response;
66-
}
67-
}
68-
export function extractErrorMessage(error: unknown): string {
69-
if (error instanceof Error) {
70-
return error.message;
71-
} else {
72-
return `${error}`;
73-
}
74-
}
75-
export function filterSet<T>(
76-
set: Iterable<readonly [condition: boolean, value: T]>,
77-
): ReadonlyArray<T> {
78-
return [...set].filter(([condition]) => condition).map(([_, value]) => value);
79-
}
8026
export function flattenError(error: unknown): ReadonlyArray<unknown> {
8127
if (error instanceof AggregateError) {
8228
return error.errors.flatMap(flattenError);
8329
} else {
8430
return [error];
8531
}
8632
}
87-
export function lazy<T>(fn: () => T): () => T {
88-
const cache = new Lazy(fn);
89-
return () => cache.getValue();
90-
}
9133
export function deduplicateErrors<T extends Error>(
9234
errors: Iterable<T>,
9335
): ReadonlyArray<T> {
9436
return distinctBy(errors, ({ message }) => message);
9537
}
96-
export function characterClass(characters: Iterable<string>): RegExp {
97-
return new RegExp(`[${escape([...characters].join(""))}]`, "u");
98-
}
99-
export function uniquePairs<T>(
100-
array: ReadonlyArray<T>,
101-
): ReadonlyArray<readonly [T, T]> {
102-
return array.flatMap((a, i) => array.slice(i + 1).map((b) => [a, b]));
103-
}
10438
export function throwError(error: unknown): never {
10539
throw error;
10640
}
107-
export function findDuplicate<T>(iterable: Iterable<T>): null | T {
108-
const set = new Set();
109-
for (const value of iterable) {
110-
if (set.has(value)) {
111-
return value;
112-
} else {
113-
set.add(value);
114-
}
115-
}
116-
return null;
117-
}

src/parser/filter.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { extractArrayResultError } from "../array_result.ts";
2-
import { findDuplicate, flattenError, throwError } from "../misc.ts";
2+
import { flattenError, throwError } from "../misc.ts";
33
import { settings } from "../settings.ts";
44
import {
55
Clause,
@@ -418,3 +418,14 @@ function phraseHasTopLevelEmphasis(phrase: Phrase): boolean {
418418
return phrase.emphasis != null;
419419
}
420420
}
421+
function findDuplicate<T>(iterable: Iterable<T>): null | T {
422+
const set = new Set();
423+
for (const value of iterable) {
424+
if (set.has(value)) {
425+
return value;
426+
} else {
427+
set.add(value);
428+
}
429+
}
430+
return null;
431+
}

src/parser/punctuation.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { characterClass } from "../misc.ts";
1+
import { escape } from "@std/regexp/escape";
22
import { UCSUR_COLON, UCSUR_MIDDLE_DOT } from "./ucsur.ts";
33

44
export const ELLIPSIS = "\u2026";
@@ -28,3 +28,7 @@ export const SENTENCE_TERMINATOR = characterClass(
2828
);
2929
export const NSK_PERIOD = characterClass(NSK_PERIOD_SET);
3030
export const NSK_COLON = characterClass(FULL_WIDTH_COLON);
31+
32+
function characterClass(characters: Iterable<string>): RegExp {
33+
return new RegExp(`[${escape([...characters].join(""))}]`, "u");
34+
}

src/parser/test.ts

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import { assertNotEquals } from "@std/assert/not-equals";
44
import { assertThrows } from "@std/assert/throws";
5-
import { uniquePairs } from "../misc.ts";
65
import { parse } from "./parser.ts";
76
import { EXAMPLE_SENTENCES, MALFORMED_SENTENCES } from "../examples.ts";
87

@@ -20,3 +19,9 @@ Deno.test("parser all error", () => {
2019
assertThrows(() => parse(sentence).unwrap());
2120
}
2221
});
22+
23+
function uniquePairs<T>(
24+
array: ReadonlyArray<T>,
25+
): ReadonlyArray<readonly [T, T]> {
26+
return array.flatMap((a, i) => array.slice(i + 1).map((b) => [a, b]));
27+
}

src/settings_frontend.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// This code is browser only
22

33
import { toKebabCase } from "@std/text/to-kebab-case";
4-
import { checkLocalStorage, setIgnoreError } from "./misc.ts";
4+
import { checkLocalStorage, setIgnoreError } from "./local_storage.ts";
55
import {
66
defaultSettings,
77
RedundancySettings,

src/translator/determiner.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { zip } from "@std/collections/zip";
22
import * as Dictionary from "../../dictionary/type.ts";
33
import { ArrayResult } from "../array_result.ts";
4-
import { filterSet } from "../misc.ts";
54
import * as English from "./ast.ts";
65
import { FilteredOutError } from "./error.ts";
76
import { simpleNounForms } from "./noun.ts";
@@ -152,3 +151,8 @@ function encodeDeterminer(
152151
.flat()
153152
.join("");
154153
}
154+
function filterSet<T>(
155+
set: Iterable<readonly [condition: boolean, value: T]>,
156+
): ReadonlyArray<T> {
157+
return [...set].filter(([condition]) => condition).map(([_, value]) => value);
158+
}

telo_misikeke/update.ts

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// This code is Deno only
22

33
import { retry } from "@std/async/retry";
4-
import { assertOk } from "../src/misc.ts";
54

65
const TELO_MISIKEKE_URL =
76
"https://gitlab.com/telo-misikeke/telo-misikeke.gitlab.io/-/raw/main/";
@@ -81,3 +80,13 @@ if (import.meta.main) {
8180
// deno-lint-ignore no-console
8281
console.log("Updated telo misikeke.");
8382
}
83+
function assertOk(response: Response): Response {
84+
if (!response.ok) {
85+
const { url, status, statusText } = response;
86+
throw new Error(
87+
`unable to fetch ${url} (${status} ${statusText})`,
88+
);
89+
} else {
90+
return response;
91+
}
92+
}

0 commit comments

Comments
 (0)