2020-02-06 02:11:26 +02:00
|
|
|
import rndstr from 'rndstr';
|
|
|
|
|
2019-04-07 15:50:36 +03:00
|
|
|
export function nyaize(text: string): string {
|
2020-02-06 02:11:26 +02:00
|
|
|
const [toNyaize, exclusionMap] = exclude(text);
|
|
|
|
const nyaized = toNyaize
|
2019-04-07 15:50:36 +03:00
|
|
|
// ja-JP
|
|
|
|
.replace(/な/g, 'にゃ').replace(/ナ/g, 'ニャ').replace(/ナ/g, 'ニャ')
|
2019-06-24 16:20:13 +03:00
|
|
|
// en-US
|
|
|
|
.replace(/morning/gi, 'mornyan').replace(/everyone/gi, 'everynyan')
|
2019-04-07 15:50:36 +03:00
|
|
|
// ko-KR
|
2019-04-12 19:43:22 +03:00
|
|
|
.replace(/[나-낳]/g, match => String.fromCharCode(
|
2020-02-06 02:11:26 +02:00
|
|
|
match.charCodeAt(0)! + '냐'.charCodeAt(0) - '나'.charCodeAt(0)
|
2020-02-05 14:11:24 +02:00
|
|
|
))
|
|
|
|
.replace(/(다$)|(다(?=\.))|(다(?= ))|(다(?=!))|(다(?=\?))/gm, '다냥')
|
|
|
|
.replace(/(야(?=\?))|(야$)|(야(?= ))/gm, '냥');
|
2020-02-06 02:11:26 +02:00
|
|
|
return replaceExceptions(nyaized, exclusionMap);
|
|
|
|
}
|
|
|
|
|
|
|
|
function exclude(text: string): [string, Record<string, string>] {
|
|
|
|
const map: Record<string, string> = {};
|
|
|
|
function substitute(match: string): string {
|
|
|
|
let randomstr: string;
|
|
|
|
do {
|
|
|
|
randomstr = rndstr({ length: 16, chars: '🀀-🀫' });
|
|
|
|
} while(Object.prototype.hasOwnProperty.call(map, randomstr));
|
|
|
|
map[randomstr] = match;
|
|
|
|
return randomstr;
|
|
|
|
}
|
|
|
|
const replaced = text
|
|
|
|
.replace(/```(.+?)?\n([\s\S]+?)```(\n|$)/gm, match => substitute(match)) // code block
|
|
|
|
.replace(/`([^`\n]+?)`/g, match => substitute(match)) // inline code
|
|
|
|
.replace(/(https?:\/\/.*?)(?= |$)/gm, match => substitute(match)) // URL
|
|
|
|
.replace(/:([a-z0-9_+-]+):/gim, match => substitute(match)) // emoji
|
|
|
|
.replace(/#([^\s.,!?'"#:\/\[\]【】]+)/gm, match => substitute(match)) // hashtag
|
|
|
|
.replace(/@\w([\w-]*\w)?(?:@[\w.\-]+\w)?/gm, match => substitute(match)); // mention
|
|
|
|
return [replaced, map];
|
|
|
|
}
|
|
|
|
|
|
|
|
function replaceExceptions(text: string, map: Record<string, string>): string {
|
|
|
|
for (const rule in map) {
|
|
|
|
if (Object.prototype.hasOwnProperty.call(map, rule)) {
|
|
|
|
text = text.replace(rule, map[rule]);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return text;
|
2019-04-07 15:50:36 +03:00
|
|
|
}
|