-
Notifications
You must be signed in to change notification settings - Fork 50
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
49 additions
and
18 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,54 @@ | ||
export type Glossary = { [key: string]: string }; | ||
|
||
export namespace Glossary { | ||
export const encodeToText = (glossary: Glossary) => { | ||
const toJson = (glossary: Glossary) => { | ||
return JSON.stringify(glossary, null, 2); | ||
}; | ||
|
||
export const decodeFromText = (text: string): Glossary | undefined => { | ||
const fromJson = (text: string): Glossary | undefined => { | ||
try { | ||
const obj = JSON.parse(text); | ||
if (typeof obj !== 'object') return; | ||
const inputGlossary: { [key: string]: string } = {}; | ||
const glossary: Glossary = {}; | ||
for (const jp in obj) { | ||
const zh = obj[jp]; | ||
if (typeof zh !== 'string') return; | ||
inputGlossary[jp] = zh; | ||
glossary[jp] = zh; | ||
} | ||
return inputGlossary; | ||
return glossary; | ||
} catch { | ||
return; | ||
} | ||
}; | ||
|
||
const delimiter = '=>'; | ||
const toHumanReadableFormat = (glossary: Glossary) => { | ||
const lines = []; | ||
for (const jp in glossary) { | ||
const zh = glossary[jp]; | ||
lines.push(`${jp} ${delimiter} ${zh}`); | ||
} | ||
return lines.join('\n'); | ||
}; | ||
const fromHumanReadableFormat = (text: string): Glossary | undefined => { | ||
const glossary: Glossary = {}; | ||
for (let line of text.split('\n')) { | ||
line = line.trim(); | ||
if (line === '') continue; | ||
|
||
const parts = line.split(delimiter); | ||
console.log(parts); | ||
if (parts.length !== 2) return; | ||
|
||
const [jp, zh] = parts; | ||
glossary[jp.trim()] = zh.trim(); | ||
} | ||
return glossary; | ||
}; | ||
|
||
export const toText = (glossary: Glossary) => { | ||
return toHumanReadableFormat(glossary); | ||
}; | ||
export const fromText = (text: string): Glossary | undefined => { | ||
return fromJson(text) ?? fromHumanReadableFormat(text); | ||
}; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters