zh-translator
Version:
147 lines (141 loc) • 9.3 kB
JavaScript
;
const lastWords = ["AAL", "abuse of franchise", "acetone pyrolysis", "across the border", "additive identity", "advance payment of income tax", "agalactosuria", "air-cooled engine", "Alfred Russel Wallace", "alloplasty", "alveolation", "amninosuccinamic acid", "anastasis", "animal electricity", "anthracosis palpebral", "antistaphylococcus sera", "applesauce cake", "arctic hare", "arrow-heads", "asami", "asteroid hyalitis", "atropisomerism", "autodiagnosis", "award sb with a medal", "back-handers", "Balfour's disease", "barilla", "bat-blind", "be insensible of", "bedizen", "benner", "beurre", "billye", "bisons", "blend(ed) fibre", "boat pan", "Boolean add", "box chamber", "breathalyze", "bronchi-", "builder's cerificates", "business credit", "cachexia mercurialis", "calogero", "caparisoned", "carcinophilia", "caryolytic", "cathode choke coil", "cementless", "cesset processus", "Charlemagne", "chg", "chlorophenetole", "chronic catarrhal laryngitis", "cistaceous", "cleistogamous", "co-culture", "coffee machine", "color code", "commission of appraisement", "complexometric titration", "condensing zone", "consignment of goods", "contraction of area", "Copperheadism", "corrugated edge", "countertide", "credentialing", "crossbenches", "cuffing", "cut wire shot", "cytocannibalism", "data communication station", "debt-holder", "defender", "dementia praesenilis", "depurate", "deterministically", "diatomic molecule", "digital network", "dipode", "diseuse", "distributions", "dolichocephalic", "douch", "drop biscuit", "duodenal stasis", "earned premium", "edgewise pointer", "election year", "eligibility", "enaction", "engrailment", "epidemic hiccup", "Erie", "ethaverine", "evalvate", "exercised", "exteriorly", "factorizes", "family Procellariidae", "feamale", "ferrous hydroxide", "filing criterion", "first team", "flavour enhancer", "fluorescence efficiency", "for the account", "forward exchange dealing", "free on board (FOB)", "frozen capital", "furfuration", "gamma granules", "gauge boson", "genus Acrocarpus", "genus Periplaneta", "get funny with", "give voice to", "glycol diacetate", "gonorrheal ketatosis", "granule layer", "grimoire", "guimond", "Hagerstown", "handsewn", "haunting", "heat value", "hemiepiphyte", "Herter's disease", "high rate discharge", "Hochard's symptom", "homophony", "hourly earnings", "Hybinette process (for nickel extraction)", "hypazoturic nephropathy", "hysteresis of adsorption", "iins", "implanted channel", "in the open", "indeterminate cleavage", "infinitely-small", "ins", "intercalary sulci", "interpenetrations", "inverse video", "irrevocable condition", "issuance", "jazziest", "Jorissen's tests", "Kalousek polarography", "keratotomy", "kirlin", "kowtowed", "lactification", "lansdale", "lauro-dimyristin", "leave in the air", "leptocephalia", "lichen psoriasis", "limited order", "liquid relief valve", "loan on personal guarantee", "longitude", "lower loop", "lymphangiomas", "Madura foot", "make a dead set at sb", "man-machine package", "Marennes", "masseurs", "mazy", "medicephalic", "Memory Stick", "Mesogonimus heterophyes", "methyl p-aminophenol", "microminiaturized", "milliampere second", "misfold", "modifiers", "monocrystal", "Morrigan", "mucinase", "multistoried", "mycoin C", "name conflict", "naval blockade", "neoreserpiline", "neutral conductor", "niman", "nominal rate of interest", "nonphysical", "nothing much", "nuzzled", "octyl phenol", "oil skimmer", "on the track", "operational readiness", "order-value search", "osmolar", "outputting", "overshooting", "pack a jury", "pancil", "paralyzing vertigo", "partial content", "paunchier", "pelorial", "perform an experiment", "persist", "phase-sequence", "Photinia arbutifolia", "piano wire", "Pinus contorta murrayana", "plante cell", "plodding", "polarization current", "polysialia", "possum haw", "power driven system", "prefetching", "preventions", "pro choice", "programmable open system", "prostyle", "pseudohemophilia", "pullery", "put on beef", "quadruple notation", "quinuclidinyl", "Radleys", "rate of call", "ready program", "recovery unit", "reflight", "relativistically", "report format", "response time requirement", "reversible encoding", "ricochetted", "robbie", "roseola scarlatiniforme", "rudimentary organs", "sacristy", "Salvia triloba L.", "satisfier", "Schering bridge", "scraped-surface exchanger", "secondary axis", "self-confidently", "senedigitalene", "servicemen", "sharp-freeze", "short saphenous vein", "Sigmodon hispidus", "single escape peak", "skip keying", "smart drug", "sodium alcoholate", "sonchus oleraceus L.", "spars", "sphygmopalpation", "spooney", "stacks", "statement form", "Stephen's spots", "stonecutters", "stricter", "subalterns", "substratum radiatum", "summarizing", "suppressive fire", "sweethread", "synsepalous", "Takata reagent", "tar acid", "teethe", "tenson", "tetranuclear", "therapeutic abortion", "Thomas Gainsborough", "tickling", "to a fractional", "top of the line", "tracheal fistula", "translator device", "triangular thread", "triploidite", "tuba", "tuyere", "ultimate balance", "under martial law", "unified file transfer", "unrecognizably", "uranosphaerite", "vacuum bag", "vase-fine", "verifiably", "vikes", "voice operating control", "walking typhoid", "waterorks", "wellington", "WHOAMI", "wire nipper", "work late into the night", "xenic acid", "youngness", "zoomers"];
function getKey(word) {
for (let i = 0; i < lastWords.length; i++) {
const lastWord = lastWords[i];
if (word.localeCompare(lastWord) <= 0) {
return i.toString().padStart(3, "0");
}
}
return "307";
}
function upperFirstChar(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function lowererFirstChar(str) {
return str.charAt(0).toLocaleLowerCase() + str.slice(1);
}
const CamelRegx = /([A-Z])/g;
function camelToSnakeLike(str) {
const firstChar = str[0];
const rest = str.slice(1);
return firstChar + rest.replace(CamelRegx, (_, letter) => "_" + letter);
}
const WhiteSpace = /\s+/;
function enumWords(word) {
const keys = /* @__PURE__ */ new Set();
if (!word) {
return keys;
}
keys.add(upperFirstChar(word));
keys.add(lowererFirstChar(word));
keys.add(word.toLowerCase());
keys.add(word.toUpperCase());
const tokens = word.split(WhiteSpace);
if (tokens.length >= 2) {
for (const token of tokens) {
const newKeys = enumWords(token);
newKeys.forEach((newKey) => newKey && keys.add(newKey));
}
}
const snakeKeys = word.split("_");
let wordWithWhite = snakeKeys.join(" ");
keys.add(wordWithWhite);
keys.add(wordWithWhite.toLowerCase());
keys.add(wordWithWhite.toUpperCase());
if (snakeKeys.length >= 2) {
for (const token of snakeKeys) {
const newKeys = enumWords(token);
newKeys.forEach((newKey) => newKey && keys.add(newKey));
}
}
const camelKeys = camelToSnakeLike(word).split("_");
wordWithWhite = camelKeys.join(" ");
keys.add(wordWithWhite);
keys.add(wordWithWhite.toLowerCase());
keys.add(wordWithWhite.toUpperCase());
if (camelKeys.length >= 2) {
for (const token of camelKeys) {
const newKeys = enumWords(token);
newKeys.forEach((newKey) => newKey && keys.add(newKey));
}
}
return keys;
}
const InflectionMap = {
p: "\u8FC7\u53BB\u5F0F",
d: "\u8FC7\u53BB\u5206\u8BCD",
i: "\u73B0\u5728\u5206\u8BCD",
3: "\u7B2C\u4E09\u4EBA\u79F0\u5355\u6570",
r: "\u6BD4\u8F83\u7EA7",
t: "\u6700\u9AD8\u7EA7",
s: "\u590D\u6570",
0: "\u539F\u578B",
1: "\u53D8\u6362\u4E3A\u539F\u578B"
};
function parseTokens(tokens, transformed) {
const results = [];
for (const token of tokens) {
const inflectionKey = token[0];
const inflectionType = InflectionMap[inflectionKey];
if (inflectionType) {
const value = token.slice(2);
if (value === transformed) {
continue;
}
results.push({ type: inflectionType, value });
}
}
return results;
}
async function parseInflection(key) {
try {
const module = await import('./chunks/inflection-data.cjs');
const inflectionData = module.default;
const inflection = inflectionData[key];
if (!inflection) {
return [];
}
const tokens = inflection.split("/");
if (inflection.includes("0:")) {
for (const token of tokens) {
if (token[0] === "0" && token[1] === ":") {
const origin = token.slice(2);
const data = inflectionData[origin];
if (data) {
return [
{ type: "\u539F\u578B", value: origin },
...parseTokens(data.split("/"), key)
];
}
}
}
}
return parseTokens(tokens);
} catch (error) {
return [];
}
}
async function translate(word) {
try {
const words = enumWords(word);
const results = await Promise.all(
[...words].map(async (word2) => {
const data = (await import(`../data/${getKey(word2)}.js`)).default;
const value = data[word2];
if (value) {
const inflection = await parseInflection(word2);
return {
word: word2,
translation: value,
inflection
};
}
})
);
return results.filter(Boolean);
} catch (error) {
return;
}
}
exports.translate = translate;