Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions dist/yopta.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

36 changes: 26 additions & 10 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,9 @@ import dictionary from './dictionary/sortedYopta.json';

function escapeRegExp(str: string) {
str = str.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

if (/^\w+$/.test(str)) {
str = '\\b' + str + '\\b';
}

return str;
}

Expand All @@ -23,14 +21,11 @@ function yoptReplaceAll(str: string, search: string, replacement: string) {
function iterateText(text: string, to: 'js' | 'ys' = 'ys') {
const langCol = to === 'ys' ? 1 : 0;
const dick = dictionary;
dick.sort((a, b) => {
const al = a[langCol].length;
const bl = b[langCol].length;
return bl - al;
}).forEach(
(pair) => (text = yoptReplaceAll(text, pair[langCol], pair[+!langCol]))
dick.sort((a, b) => b[langCol].length - a[langCol].length).forEach(
(pair) => {
text = yoptReplaceAll(text, pair[langCol], pair[+!langCol]);
}
);

return text;
}

Expand All @@ -47,25 +42,46 @@ export function compile(text: string, lang: 'js' | 'ys' = 'ys'): string {
interface Literals {
[key: string]: string;
}
const rJsxTextLiterals: Literals = {};
text = text.replace(
/(<[A-Za-z][^>]*>)([\s\S]+?)(?=<\/[A-Za-z])/g,
(_, openTag, content, offset) => {
const key = tmpToken + 'jsx_' + offset;
rJsxTextLiterals[key] = content;
return openTag + key;
}
);

const commentRegExp = /((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/g;
const tmpToken = 'ys_' + new Date().getTime() + '_';

const rStringLiterals: Literals = {};
text = text.replace(
/\"(?:\\.|[^\"\\])*\"|\'(?:\\.|[^\'\\])*\'/g,
function (val, pos) {
(val, pos) => {
const needKey = tmpToken + pos;
rStringLiterals[needKey] = val;
return needKey;
}
);

const commentsArray = text.match(commentRegExp) || [];

text = iterateText(text, lang);

// comeback comments
text = text.replace(commentRegExp, () => commentsArray.shift() || '');

// comeback strings
for (const key in rStringLiterals) {
text = text.replace(key, rStringLiterals[key]);
}

// comeback jsx
for (const key in rJsxTextLiterals) {
text = text.replace(key, rJsxTextLiterals[key]);
}

return text;
}

Expand Down
2 changes: 1 addition & 1 deletion src/dictionary/dictionary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,6 @@ export const dictionary = [
// NodeJS/modules support
['module', 'братва'],
['exports', 'предъявляет'],
['export', 'предъявa'],
['export', 'предъява'],
['global', 'общак'],
];