Обновление всех файлов с ESLint
This commit is contained in:
+17
-12
@@ -1,6 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import { JokerClass } from "../joker";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import $ from 'jquery';
|
||||
|
||||
/**
|
||||
* **Карнавал**
|
||||
@@ -10,14 +9,17 @@ import { JokerClass } from "../joker";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class CarnivalJoke extends Joke<CarnivalJokeSettings> {
|
||||
id = "carnival";
|
||||
id = 'carnival';
|
||||
|
||||
title = "Карнавал";
|
||||
title = 'Карнавал';
|
||||
|
||||
description = "Аватарки приобретают интересные цвета";
|
||||
description = 'Аватарки приобретают интересные цвета';
|
||||
|
||||
_settings = new CarnivalJokeSettings();
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
$(this.settings.selector).each((_, elem) => {
|
||||
const filters: string[] = [];
|
||||
@@ -29,19 +31,22 @@ export class CarnivalJoke extends Joke<CarnivalJokeSettings> {
|
||||
|
||||
filters.push(
|
||||
entry[0].replace(
|
||||
"{0}",
|
||||
'{0}',
|
||||
Math.round(Math.random() * entry[1]).toString()
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (filters.length > 0) {
|
||||
$(elem).css({ filter: filters.join(" ") });
|
||||
$(elem).css({filter: filters.join(' ')});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Карнавал"
|
||||
*/
|
||||
export class CarnivalJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
|
||||
@@ -61,10 +66,10 @@ export class CarnivalJokeSettings implements JokeSettings {
|
||||
* Список фильтров и диапозона случайных параметров
|
||||
*/
|
||||
variants: CarnivalJokeFilters = {
|
||||
"sepia({0}%)": 100,
|
||||
"saturate({0}%)": 100,
|
||||
"hue-rotate({0}deg)": 360,
|
||||
"invert({0}%)": 100,
|
||||
'sepia({0}%)': 100,
|
||||
'saturate({0}%)': 100,
|
||||
'hue-rotate({0}deg)': 360,
|
||||
'invert({0}%)': 100,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import $ from 'jquery';
|
||||
|
||||
/**
|
||||
* **Мама, Я сОшЛа С уМа!**
|
||||
@@ -9,21 +9,24 @@ import $ from "jquery";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class CrazyLettersJoke extends Joke<CrazyLettersJokeSettings> {
|
||||
id = "crazy_letters";
|
||||
id = 'crazy_letters';
|
||||
|
||||
title = "Мама, Я сОшЛа С уМа!";
|
||||
title = 'Мама, Я сОшЛа С уМа!';
|
||||
|
||||
description = "иМеНа ЗаБоРчИкОм";
|
||||
description = 'иМеНа ЗаБоРчИкОм';
|
||||
|
||||
_settings = new CrazyLettersJokeSettings();
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
$(this.settings.selector).each((_, elem) => {
|
||||
let text = $(this).text();
|
||||
let result = "";
|
||||
const text = $(elem).text();
|
||||
let result = '';
|
||||
|
||||
for (let i = 0; i < text.length; i++) {
|
||||
result += text[i][i % 2 ? "toLowerCase" : "toUpperCase"]();
|
||||
result += text[i][i % 2 ? 'toLowerCase' : 'toUpperCase']();
|
||||
}
|
||||
|
||||
$(this).text(result);
|
||||
@@ -31,6 +34,9 @@ export class CrazyLettersJoke extends Joke<CrazyLettersJokeSettings> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Мама, Я сОшЛа С уМа!"
|
||||
*/
|
||||
export class CrazyLettersJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
|
||||
@@ -39,5 +45,5 @@ export class CrazyLettersJokeSettings implements JokeSettings {
|
||||
/**
|
||||
* Селектор всех элементов, которые будут затронуты
|
||||
*/
|
||||
selector: string = ".pa-author a";
|
||||
selector: string = '.pa-author a';
|
||||
}
|
||||
|
||||
+99
-67
@@ -1,8 +1,8 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import { Interface } from "readline";
|
||||
// import * as cursor_effects from "cursor-effects";
|
||||
const cursor_effects = require("cursor-effects");
|
||||
|
||||
import {JokeSettings, StoppableJoke} from '../joke';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-var-requires
|
||||
import * as CursorEffectsLib from 'cursor-effects';
|
||||
|
||||
/**
|
||||
* **Красивый курсор**
|
||||
@@ -12,16 +12,17 @@ const cursor_effects = require("cursor-effects");
|
||||
* @author Tim Holman
|
||||
* @link https://tholman.com/cursor-effects/
|
||||
*/
|
||||
export class CursorEffectsJoke extends StopableJoke<CursorEffectsJokeSettings> {
|
||||
id = "cursor_effects";
|
||||
export class CursorEffectsJoke extends
|
||||
StoppableJoke<CursorEffectsJokeSettings> {
|
||||
id = 'cursor_effects';
|
||||
|
||||
title = "Красивый курсор";
|
||||
title = 'Красивый курсор';
|
||||
|
||||
description = "Эффекты, следующие за курсором";
|
||||
description = 'Эффекты, следующие за курсором';
|
||||
|
||||
_settings = new CursorEffectsJokeSettings();
|
||||
|
||||
active_cursor_effect: any;
|
||||
active_cursor_effect: CursorEffectsLib.CursorEffectResult;
|
||||
|
||||
/**
|
||||
* Разблокировать все варианты курсоров
|
||||
@@ -41,11 +42,21 @@ export class CursorEffectsJoke extends StopableJoke<CursorEffectsJokeSettings> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение веса отдельного эффекта
|
||||
* @param {CursorEffectsEnum} effect Тип эффекта
|
||||
* @return {number} Значение веса
|
||||
* @private
|
||||
*/
|
||||
private weight(effect: CursorEffectsEnum): number {
|
||||
const s = this.settings.effects[effect];
|
||||
return s.enabled ? s.weight : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение случайного эффекта
|
||||
* @return {CursorEffectsEnum}
|
||||
*/
|
||||
getRandomEffect(): CursorEffectsEnum {
|
||||
const elements = Object.values(CursorEffectsEnum).map(
|
||||
(e) => <CursorEffectsEnum>e
|
||||
@@ -64,9 +75,12 @@ export class CursorEffectsJoke extends StopableJoke<CursorEffectsJokeSettings> {
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Тебя быть тут не должно...");
|
||||
throw new Error('Тебя быть тут не должно...');
|
||||
}
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
const effect = this.getRandomEffect();
|
||||
const settings = this.settings.effects[effect];
|
||||
@@ -74,65 +88,77 @@ export class CursorEffectsJoke extends StopableJoke<CursorEffectsJokeSettings> {
|
||||
this.active_cursor_effect = resolveCursorEffectsEnum(effect, settings);
|
||||
}
|
||||
|
||||
/**
|
||||
* Остановка шутки
|
||||
*/
|
||||
stop(): void {
|
||||
this.active_cursor_effect.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
enum CursorEffectsEnum {
|
||||
Rainbow = "rainbow",
|
||||
FairyDust = "fairy_dust",
|
||||
SpringyEmoji = "springy_emoji",
|
||||
Emoji = "emoji",
|
||||
Ghost = "ghost",
|
||||
Trailing = "trailing",
|
||||
TextFlag = "text_flag",
|
||||
FollowingDot = "following_dot",
|
||||
Bubbles = "bubbles",
|
||||
Snowflake = "snowflake",
|
||||
Clock = "clock",
|
||||
Rainbow = 'rainbow',
|
||||
FairyDust = 'fairy_dust',
|
||||
SpringyEmoji = 'springy_emoji',
|
||||
Emoji = 'emoji',
|
||||
Ghost = 'ghost',
|
||||
Trailing = 'trailing',
|
||||
TextFlag = 'text_flag',
|
||||
FollowingDot = 'following_dot',
|
||||
Bubbles = 'bubbles',
|
||||
Snowflake = 'snowflake',
|
||||
Clock = 'clock',
|
||||
}
|
||||
|
||||
/**
|
||||
* Получение эффекта
|
||||
* @param {CursorEffectsEnum | string} effect Тип эффекта
|
||||
* @param {CursorEffectsSetting} options Настройки эффекта
|
||||
* @return {CursorEffectsLib.CursorEffectResult}
|
||||
*/
|
||||
function resolveCursorEffectsEnum(
|
||||
effect: CursorEffectsEnum | string,
|
||||
options: CursorEffectsSetting
|
||||
): any {
|
||||
): CursorEffectsLib.CursorEffectResult {
|
||||
switch (effect) {
|
||||
case CursorEffectsEnum.Rainbow:
|
||||
return cursor_effects.rainbowCursor(options);
|
||||
return CursorEffectsLib.rainbowCursor(options);
|
||||
|
||||
case CursorEffectsEnum.FairyDust:
|
||||
return cursor_effects.fairyDustCursor(options);
|
||||
return CursorEffectsLib.fairyDustCursor(options);
|
||||
|
||||
case CursorEffectsEnum.SpringyEmoji:
|
||||
return cursor_effects.springyEmojiCursor(options);
|
||||
return CursorEffectsLib.springyEmojiCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Emoji:
|
||||
return cursor_effects.emojiCursor(options);
|
||||
return CursorEffectsLib.emojiCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Ghost:
|
||||
return cursor_effects.ghostCursor(options);
|
||||
return CursorEffectsLib.ghostCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Trailing:
|
||||
return cursor_effects.trailingCursor(options);
|
||||
return CursorEffectsLib.trailingCursor(options);
|
||||
|
||||
case CursorEffectsEnum.TextFlag:
|
||||
return cursor_effects.textFlag(options);
|
||||
return CursorEffectsLib.textFlag(options);
|
||||
|
||||
case CursorEffectsEnum.FollowingDot:
|
||||
return cursor_effects.followingDotCursor(options);
|
||||
return CursorEffectsLib.followingDotCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Bubbles:
|
||||
return cursor_effects.bubbleCursor(options);
|
||||
return CursorEffectsLib.bubbleCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Snowflake:
|
||||
return cursor_effects.snowflakeCursor(options);
|
||||
return CursorEffectsLib.snowflakeCursor(options);
|
||||
|
||||
case CursorEffectsEnum.Clock:
|
||||
return cursor_effects.clockCursor(options);
|
||||
return CursorEffectsLib.clockCursor(options);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Красивый курсор"
|
||||
*/
|
||||
export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
|
||||
@@ -143,7 +169,7 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Радужный след за курсором
|
||||
*/
|
||||
[CursorEffectsEnum.Rainbow]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Длина полосы
|
||||
*/
|
||||
@@ -158,13 +184,13 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Цвета полос (сверху вниз)
|
||||
*/
|
||||
colors: string[] = [
|
||||
"#9400D3",
|
||||
"#4B0082",
|
||||
"#0000FF",
|
||||
"#00FF00",
|
||||
"#FFFF00",
|
||||
"#FF7F00",
|
||||
"#FF0000",
|
||||
'#9400D3',
|
||||
'#4B0082',
|
||||
'#0000FF',
|
||||
'#00FF00',
|
||||
'#FFFF00',
|
||||
'#FF7F00',
|
||||
'#FF0000',
|
||||
];
|
||||
})(),
|
||||
|
||||
@@ -172,44 +198,44 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Цепочка из эмодзи "на резинке" под курсором
|
||||
*/
|
||||
[CursorEffectsEnum.SpringyEmoji]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Висящий эмодзи
|
||||
*/
|
||||
emoji: string = "🤪";
|
||||
emoji: string = '🤪';
|
||||
})(),
|
||||
|
||||
/**
|
||||
* Падающие от курсора эмодзи
|
||||
*/
|
||||
[CursorEffectsEnum.Emoji]: new (class extends DefaultCursorEffectsSetting {
|
||||
[CursorEffectsEnum.Emoji]: new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Падающие эмодзи
|
||||
*/
|
||||
emoji: string[] = ["🔥", "🐬", "🦆"];
|
||||
emoji: string[] = ['🔥', '🐬', '🦆'];
|
||||
})(),
|
||||
|
||||
/**
|
||||
* Падающие от курсора пылинки
|
||||
*/
|
||||
[CursorEffectsEnum.FairyDust]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Цвет пылинок
|
||||
*/
|
||||
colors: string[] = ["#ff0000", "#00ff00", "#0000ff"];
|
||||
colors: string[] = ['#ff0000', '#00ff00', '#0000ff'];
|
||||
})(),
|
||||
|
||||
/**
|
||||
* След "зависших" курсоров
|
||||
*/
|
||||
[CursorEffectsEnum.Ghost]: new DefaultCursorEffectsSetting(),
|
||||
[CursorEffectsEnum.Ghost]: new CursorEffectsSetting(),
|
||||
|
||||
/**
|
||||
* След курсоров "на резинке"
|
||||
*/
|
||||
[CursorEffectsEnum.Trailing]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Количество элементов
|
||||
*/
|
||||
@@ -231,21 +257,21 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Текст, развивающийся флагом от курсора
|
||||
*/
|
||||
[CursorEffectsEnum.TextFlag]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Отображаемый текст
|
||||
*/
|
||||
text: string = "С днём смеха!";
|
||||
text: string = 'С днём смеха!';
|
||||
|
||||
/**
|
||||
* Цвет текста
|
||||
*/
|
||||
color: string = "#000000";
|
||||
color: string = '#000000';
|
||||
|
||||
/**
|
||||
* Шрифт текста
|
||||
*/
|
||||
font: string = "monospace";
|
||||
font: string = 'monospace';
|
||||
|
||||
/**
|
||||
* Размер текста
|
||||
@@ -267,17 +293,17 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Точка, преследующая курсор
|
||||
*/
|
||||
[CursorEffectsEnum.FollowingDot]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Цвет догоняющей точки
|
||||
*/
|
||||
color: string = "#323232a6";
|
||||
color: string = '#323232a6';
|
||||
})(),
|
||||
|
||||
/**
|
||||
* Пузырьки от курсора
|
||||
*/
|
||||
[CursorEffectsEnum.Bubbles]: new DefaultCursorEffectsSetting(),
|
||||
[CursorEffectsEnum.Bubbles]: new CursorEffectsSetting(),
|
||||
|
||||
/**
|
||||
* Снежинки, летящие от курсора
|
||||
@@ -285,47 +311,53 @@ export class CursorEffectsJokeSettings implements JokeSettings {
|
||||
* Отключено, потому что сейчас не зима :D
|
||||
*/
|
||||
[CursorEffectsEnum.Snowflake]:
|
||||
new (class extends DefaultCursorEffectsSetting {
|
||||
new (class extends CursorEffectsSetting {
|
||||
weight: number = 0;
|
||||
})(),
|
||||
|
||||
/**
|
||||
* Циферблат вокруг курсора
|
||||
*/
|
||||
[CursorEffectsEnum.Clock]: new (class extends DefaultCursorEffectsSetting {
|
||||
[CursorEffectsEnum.Clock]: new (class extends CursorEffectsSetting {
|
||||
/**
|
||||
* Цвет даты
|
||||
*/
|
||||
dateColor: string = "blue";
|
||||
dateColor: string = 'blue';
|
||||
|
||||
/**
|
||||
* Цвет циферблата
|
||||
*/
|
||||
faceColor: string = "black";
|
||||
faceColor: string = 'black';
|
||||
|
||||
/**
|
||||
* Цвет секундной стрелки
|
||||
*/
|
||||
secondsColor: string = "red";
|
||||
secondsColor: string = 'red';
|
||||
|
||||
/**
|
||||
* Цвет минутной стрелки
|
||||
*/
|
||||
minutesColor: string = "black";
|
||||
minutesColor: string = 'black';
|
||||
|
||||
/**
|
||||
* Цвет часовой стрелки
|
||||
*/
|
||||
hoursColor: string = "black";
|
||||
hoursColor: string = 'black';
|
||||
})(),
|
||||
};
|
||||
}
|
||||
|
||||
interface CursorEffectsSetting {
|
||||
[key: string]: any;
|
||||
/**
|
||||
* Восстановление класса CursorEffectsLib.DefaultOptions
|
||||
*/
|
||||
class DefaultOptions {
|
||||
readonly element?: HTMLElement;
|
||||
}
|
||||
|
||||
class DefaultCursorEffectsSetting implements CursorEffectsSetting {
|
||||
/**
|
||||
* Класс настроек для курсора
|
||||
*/
|
||||
class CursorEffectsSetting extends DefaultOptions {
|
||||
/**
|
||||
* Флаг возможности срабатывания
|
||||
*/
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import { getTextNodes } from "../common";
|
||||
import $ from "jquery";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import {getTextNodes} from '../common';
|
||||
|
||||
/**
|
||||
* **Ад гуманитария**
|
||||
@@ -10,20 +9,29 @@ import $ from "jquery";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class HumanitarianHellJoke extends Joke<HumanitarianHellJokeSettings> {
|
||||
id = "humanitarian_hell";
|
||||
id = 'humanitarian_hell';
|
||||
|
||||
title = "Ад гуманитария";
|
||||
title = 'Ад гуманитария';
|
||||
|
||||
description = 'Все "тся" заменяются на "ться", а все "ться" на "тся"';
|
||||
|
||||
_settings = new HumanitarianHellJokeSettings();
|
||||
|
||||
/**
|
||||
* Обработка текста
|
||||
*
|
||||
* @param {string} text Входная строка
|
||||
* @return {string} Итоговая строка
|
||||
*/
|
||||
processText(text: string): string {
|
||||
return text.replace(/(ть?ся)/g, function (fnd) {
|
||||
return fnd.indexOf("ь") > 0 ? "тся" : "ться";
|
||||
return text.replace(/(ть?ся)/g, function(fnd) {
|
||||
return fnd.indexOf('ь') > 0 ? 'тся' : 'ться';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
const textNodes = getTextNodes(this.settings.selector);
|
||||
|
||||
@@ -33,6 +41,9 @@ export class HumanitarianHellJoke extends Joke<HumanitarianHellJokeSettings> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Ад гуманитария"
|
||||
*/
|
||||
export class HumanitarianHellJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
|
||||
@@ -41,5 +52,5 @@ export class HumanitarianHellJokeSettings implements JokeSettings {
|
||||
/**
|
||||
* Селектор всех элементов, которые будут затронуты
|
||||
*/
|
||||
selector: string = ".post-content";
|
||||
selector: HTMLElement | JQuery<HTMLElement> | string = '.post-content';
|
||||
}
|
||||
|
||||
+29
-18
@@ -1,7 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import { getTextNodes } from "../common";
|
||||
import $ from "jquery";
|
||||
import { JokerClass } from "../joker";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import {getTextNodes} from '../common';
|
||||
|
||||
/**
|
||||
* **Буквенный хаос**
|
||||
@@ -11,26 +9,29 @@ import { JokerClass } from "../joker";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class LetterChaosJoke extends Joke<LetterChaosJokeSettings> {
|
||||
id = "letter_chaos";
|
||||
id = 'letter_chaos';
|
||||
|
||||
title = "Буквенный хаос";
|
||||
title = 'Буквенный хаос';
|
||||
|
||||
description = 'Все буквы в словах, кроме первой и последней, перемешены';
|
||||
|
||||
description = "Все буквы в словах, кроме первой и последней, перемешены";
|
||||
|
||||
_settings = new LetterChaosJokeSettings();
|
||||
|
||||
punctuationSymbols: string[] | null = null;
|
||||
|
||||
/**
|
||||
* Перемешивание букв в словах
|
||||
* @param {string} word
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
private shuffleLetters(word: string): string {
|
||||
// Check if the word has two or more letters
|
||||
if (word.length < 3 || !this.check(this.settings.shuffle_chance)) {
|
||||
return word;
|
||||
}
|
||||
|
||||
// Split the word into an array of characters
|
||||
const characters = word.split("");
|
||||
const characters = word.split('');
|
||||
|
||||
// Shuffle the characters between the first and last letters
|
||||
const middleCharacters = characters.slice(1, -1);
|
||||
for (let i = middleCharacters.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
@@ -40,28 +41,38 @@ export class LetterChaosJoke extends Joke<LetterChaosJokeSettings> {
|
||||
];
|
||||
}
|
||||
|
||||
// Join the shuffled characters back into a word
|
||||
return [
|
||||
characters[0],
|
||||
...middleCharacters,
|
||||
characters[characters.length - 1],
|
||||
].join("");
|
||||
].join('');
|
||||
}
|
||||
|
||||
private processNode(node: any) {
|
||||
/**
|
||||
* Обработка текстовой ноды
|
||||
* @param {Text} node
|
||||
* @private
|
||||
*/
|
||||
private processNode(node: Text) {
|
||||
node.textContent = node.textContent?.replace(
|
||||
/([А-Яа-яA-Za-z]+)/gm,
|
||||
(_: any, word: string) => this.shuffleLetters(word)
|
||||
(_: string, word: string) => this.shuffleLetters(word)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
const textNodes = getTextNodes(this.settings.selector);
|
||||
|
||||
textNodes.each((_, node) => this.processNode(node));
|
||||
textNodes.each((_, node) => this.processNode(node as Text));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Буквенный хаос"
|
||||
*/
|
||||
export class LetterChaosJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
|
||||
@@ -70,7 +81,7 @@ export class LetterChaosJokeSettings implements JokeSettings {
|
||||
/**
|
||||
* Селектор всех элементов, которые будут затронуты
|
||||
*/
|
||||
selector: string = ".post-content";
|
||||
selector: string = '.post-content';
|
||||
|
||||
/**
|
||||
* Вероятность того, что буквы будут перемешаны
|
||||
|
||||
+19
-13
@@ -1,5 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import $ from 'jquery';
|
||||
|
||||
/**
|
||||
* **Зеркало**
|
||||
@@ -9,26 +9,32 @@ import $ from "jquery";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class MirrorJoke extends Joke<MirrorJokeSettings> {
|
||||
id = "mirror";
|
||||
id = 'mirror';
|
||||
|
||||
title = "Зеркало";
|
||||
title = 'Зеркало';
|
||||
|
||||
description = "Элементы форума отражаются (по крайней мере, пытаются)";
|
||||
description = 'Элементы форума отражаются (по крайней мере, пытаются)';
|
||||
|
||||
_settings = new MirrorJokeSettings();
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
$(".post, .post h3, .post-links, .post-author, .post-content")
|
||||
.css("transform", "scaleX(-1)")
|
||||
.css("-moz-transform", "scaleX(-1)")
|
||||
.css("-moz-transform", "scaleX(-1)")
|
||||
.css("filter", "FlipH")
|
||||
.css("-ms-filter", '"FlipH"');
|
||||
$(".post-links, .post-links ul, .post h3 span").css("margin-left", "0");
|
||||
$(".post h3 span").css("margin-right", "25em");
|
||||
$('.post, .post h3, .post-links, .post-author, .post-content')
|
||||
.css('transform', 'scaleX(-1)')
|
||||
.css('-moz-transform', 'scaleX(-1)')
|
||||
.css('-moz-transform', 'scaleX(-1)')
|
||||
.css('filter', 'FlipH')
|
||||
.css('-ms-filter', '"FlipH"');
|
||||
$('.post-links, .post-links ul, .post h3 span').css('margin-left', '0');
|
||||
$('.post h3 span').css('margin-right', '25em');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Зеркало"
|
||||
*/
|
||||
export class MirrorJokeSettings implements JokeSettings {
|
||||
enabled: boolean = false;
|
||||
|
||||
|
||||
+36
-21
@@ -1,5 +1,5 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import {JokeSettings, StoppableJoke} from '../joke';
|
||||
import $ from 'jquery';
|
||||
|
||||
/**
|
||||
* **Форумо-трясение**
|
||||
@@ -8,73 +8,88 @@ import $ from "jquery";
|
||||
*
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class ShakeJoke extends StopableJoke<ShakeJokeSettings> {
|
||||
id = "shake";
|
||||
export class ShakeJoke extends StoppableJoke<ShakeJokeSettings> {
|
||||
id = 'shake';
|
||||
|
||||
title = "Форумо-трясение";
|
||||
title = 'Форумо-трясение';
|
||||
|
||||
description = "Страница форума начинает трястись";
|
||||
description = 'Страница форума начинает трястись';
|
||||
|
||||
_settings = new ShakeJokeSettings();
|
||||
|
||||
private interval_id: NodeJS.Timer;
|
||||
private intervalId: NodeJS.Timeout;
|
||||
|
||||
private items: JQuery;
|
||||
|
||||
private data_name: string = "april-fools-shake";
|
||||
private dataName: string = 'april-fools-shake';
|
||||
|
||||
/**
|
||||
* Выбор случайной амплитуды
|
||||
* @param {number} a
|
||||
* @return {number}
|
||||
*/
|
||||
rand(a: number): number {
|
||||
return a + this.settings.force * (Math.random() * 2 - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
start(): void {
|
||||
this.items = $(this.settings.selector);
|
||||
|
||||
this.items.each((_, elem) => {
|
||||
let data: ShakeJokeMargin = {};
|
||||
const data: ShakeJokeMargin = {};
|
||||
|
||||
this.settings.directions.forEach((d) => {
|
||||
data[d] = parseInt($(elem).css("margin-" + d));
|
||||
data[d] = parseInt($(elem).css('margin-' + d));
|
||||
});
|
||||
|
||||
$(elem).data(this.data_name, data);
|
||||
$(elem).data(this.dataName, data);
|
||||
});
|
||||
|
||||
this.interval_id = setInterval(() => {
|
||||
this.intervalId = setInterval(() => {
|
||||
this.items.each((_, elem) => {
|
||||
const data: ShakeJokeMargin = $(elem).data(this.data_name);
|
||||
const data: ShakeJokeMargin = $(elem).data(this.dataName);
|
||||
|
||||
for (const entry of Object.entries(data)) {
|
||||
$(elem).css("margin-" + entry[0], this.rand(entry[1]));
|
||||
$(elem).css('margin-' + entry[0], this.rand(entry[1]));
|
||||
}
|
||||
});
|
||||
}, this.settings.interval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Остновка шутки
|
||||
*/
|
||||
stop(): void {
|
||||
clearInterval(this.interval_id);
|
||||
clearInterval(this.intervalId);
|
||||
|
||||
this.items.each((_, elem) => {
|
||||
let data: ShakeJokeMargin = {};
|
||||
const data: ShakeJokeMargin = {};
|
||||
|
||||
this.settings.directions.forEach((d) => {
|
||||
$(elem).css("margin-" + d, data[d]);
|
||||
$(elem).css('margin-' + d, data[d]);
|
||||
});
|
||||
|
||||
$(elem).data(this.data_name, data);
|
||||
$(elem).data(this.dataName, data);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Форумо-трясение"
|
||||
*/
|
||||
export class ShakeJokeSettings implements JokeSettings {
|
||||
enabled: boolean = false;
|
||||
|
||||
chance: number = 1;
|
||||
|
||||
/**
|
||||
* Направление тряски (тряска происходит путём изменения перечисленных направлений margin на значение ±force от стандартного значения)
|
||||
* Направление тряски (тряска происходит путём изменения перечисленных
|
||||
* направлений margin на значение ±force от стандартного значения)
|
||||
*/
|
||||
directions: string[] = ["top", "left", "bottom", "left"];
|
||||
directions: string[] = ['top', 'left', 'bottom', 'left'];
|
||||
|
||||
/**
|
||||
* Сила тряски - насколько отклоняется элемент от стандартного значения
|
||||
@@ -84,7 +99,7 @@ export class ShakeJokeSettings implements JokeSettings {
|
||||
/**
|
||||
* Селектор всех элементов, которые будут трястись
|
||||
*/
|
||||
selector: string = "[id^=pun]";
|
||||
selector: string = '[id^=pun]';
|
||||
|
||||
/**
|
||||
* Частота тряски
|
||||
|
||||
+197
-108
@@ -1,6 +1,6 @@
|
||||
import { Joke, JokeSettings, StopableJoke } from "../joke";
|
||||
import $ from "jquery";
|
||||
import { StupidTitleDefaultVariants } from "../data/stupid_title_variants";
|
||||
import {Joke, JokeSettings} from '../joke';
|
||||
import $ from 'jquery';
|
||||
import {StupidTitleDefaultVariants} from '../data/stupid_title_variants';
|
||||
|
||||
/**
|
||||
* **Глупые статусы**
|
||||
@@ -10,30 +10,35 @@ import { StupidTitleDefaultVariants } from "../data/stupid_title_variants";
|
||||
* @author Kozhilya
|
||||
*/
|
||||
export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
id = "stupid_title";
|
||||
id = 'stupid_title';
|
||||
|
||||
title = "Глупые статусы";
|
||||
title = 'Глупые статусы';
|
||||
|
||||
description = "Каждому пользователю даётся новый глупый статус";
|
||||
description = 'Каждому пользователю даётся новый глупый статус';
|
||||
|
||||
_settings = new StupidTitleJokeSettings();
|
||||
|
||||
private loadedGenders: any = null;
|
||||
private loadedGenders: { [key in string]: boolean } = null;
|
||||
private variantsGenerated = false;
|
||||
private seed = 0;
|
||||
|
||||
/**
|
||||
* Загрузка полов, если они не определены
|
||||
*/
|
||||
async loadGenders(): Promise<void> {
|
||||
const names = $(".pa-author a")
|
||||
.map((_, elem) => elem.innerText)
|
||||
.toArray()
|
||||
.reduce((arr: string[], name: string) => {
|
||||
if (arr.indexOf(name) < 0) {
|
||||
arr.push(name);
|
||||
}
|
||||
return arr;
|
||||
}, []);
|
||||
const names = $('.pa-author a').
|
||||
map((_, elem) => elem.innerText).
|
||||
toArray().
|
||||
reduce((arr: string[], name: string) => {
|
||||
if (arr.indexOf(name) < 0) {
|
||||
arr.push(name);
|
||||
}
|
||||
return arr;
|
||||
}, []);
|
||||
|
||||
const url =
|
||||
"/api.php?" +
|
||||
$.param({ method: "users.get", fields: "username,sex", username: names });
|
||||
'/api.php?' +
|
||||
$.param({method: 'users.get', fields: 'username,sex', username: names});
|
||||
const response = await fetch(url);
|
||||
const json = await response.json();
|
||||
|
||||
@@ -43,15 +48,21 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
return;
|
||||
}
|
||||
|
||||
json.response.users.forEach((element: any) => {
|
||||
if (element.sex === "0") {
|
||||
return;
|
||||
}
|
||||
json.response?.users.forEach(
|
||||
(element: { username: string, sex: string }) => {
|
||||
if (element.sex === '0') {
|
||||
return;
|
||||
}
|
||||
|
||||
this.loadedGenders[element.username] = element.sex === "1";
|
||||
});
|
||||
this.loadedGenders[element.username] = element.sex === '1';
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Разрешение пола по имени
|
||||
* @param {string} name
|
||||
* @return {boolean}
|
||||
*/
|
||||
resolveGender(name: string): boolean {
|
||||
if (this.settings.gender_resolver !== null) {
|
||||
return !!this.settings.gender_resolver.call(this, name);
|
||||
@@ -62,11 +73,12 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
}
|
||||
|
||||
this.resetSeed();
|
||||
return this.selectRandom(name, { m: 1, f: 1 }) === "m";
|
||||
return this.selectRandom(name, {m: 1, f: 1}) === 'm';
|
||||
}
|
||||
|
||||
private variantsGenerated = false;
|
||||
|
||||
/**
|
||||
* Запуск шутки
|
||||
*/
|
||||
async start(): Promise<void> {
|
||||
if (!this.variantsGenerated) {
|
||||
StupidTitleDefaultVariants(this.settings.variants);
|
||||
@@ -75,10 +87,10 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
|
||||
await this.loadGenders();
|
||||
|
||||
const cache: any = {};
|
||||
const cache: {[key in string]: string} = {};
|
||||
|
||||
$(".post-author").each((_, root) => {
|
||||
const name = $(".pa-author a", root).text();
|
||||
$('.post-author').each((_, root) => {
|
||||
const name = $('.pa-author a', root).text();
|
||||
if (!name) {
|
||||
return;
|
||||
}
|
||||
@@ -88,40 +100,68 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
cache[name] = this.generatePhrase(name);
|
||||
}
|
||||
|
||||
$(".pa-title", root).text(cache[name]);
|
||||
$('.pa-title', root).text(cache[name]);
|
||||
});
|
||||
}
|
||||
|
||||
private prng(name: string, seed: number, limit: number): number {
|
||||
/*
|
||||
https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
|
||||
/**
|
||||
* Сгенерировать фразу
|
||||
* @param {string} name Имя, кому необходимо сгенерировать фразу
|
||||
* @return {string} Итоговая фраза
|
||||
*/
|
||||
generatePhrase(name: string): string {
|
||||
const gender = this.resolveGender(name);
|
||||
const phrase = this.selectRandom(name, this.settings.schemas);
|
||||
|
||||
cyrb53 (c) 2018 bryc (github.com/bryc)
|
||||
A fast and simple hash function with decent collision resistance.
|
||||
Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
|
||||
Public domain. Attribution appreciated.
|
||||
*/
|
||||
let h1 = 0xdeadbeef ^ seed,
|
||||
h2 = 0x41c6ce57 ^ seed;
|
||||
return this.capitalizeFirst(
|
||||
phrase.replace(/\{(.+?)}/g, (_, type: string) => {
|
||||
const variants = this.buildVariants(type, gender);
|
||||
|
||||
return this.selectRandom(name, variants);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Функция хеширования
|
||||
*
|
||||
* https://github.com/bryc/code/blob/master/jshash/experimental/cyrb53.js
|
||||
*
|
||||
* cyrb53 (c) 2018 bryc (github.com/bryc)
|
||||
* A fast and simple hash function with decent collision resistance.
|
||||
* Largely inspired by MurmurHash2/3, but with a focus on speed/simplicity.
|
||||
* Public domain. Attribution appreciated.
|
||||
*
|
||||
* @param {string} name Имя
|
||||
* @param {number} seed Зерно случайности
|
||||
* @param {limit} limit Максимальное значение
|
||||
* @return {number} Хеш-значение
|
||||
* @private
|
||||
*/
|
||||
private prng(name: string, seed: number, limit: number): number {
|
||||
let h1 = 0xdeadbeef ^ seed;
|
||||
let h2 = 0x41c6ce57 ^ seed;
|
||||
for (let i = 0, ch; i < name.length; i++) {
|
||||
ch = name.charCodeAt(i);
|
||||
h1 = Math.imul(h1 ^ ch, 2654435761);
|
||||
h2 = Math.imul(h2 ^ ch, 1597334677);
|
||||
}
|
||||
h1 =
|
||||
Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^
|
||||
Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
||||
Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^
|
||||
Math.imul(h2 ^ (h2 >>> 13), 3266489909);
|
||||
h2 =
|
||||
Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^
|
||||
Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
||||
Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^
|
||||
Math.imul(h1 ^ (h1 >>> 13), 3266489909);
|
||||
|
||||
const value = 4294967296 * (2097151 & h2) + (h1 >>> 0);
|
||||
|
||||
return Math.floor(Math.pow(Math.sin(value), 2) * limit) % limit;
|
||||
}
|
||||
|
||||
private seed = 0;
|
||||
|
||||
/**
|
||||
* Сброс зерна случайности
|
||||
* @private
|
||||
*/
|
||||
private resetSeed(): void {
|
||||
const date = new Date();
|
||||
const time = date.getUTCHours() * 60 + date.getUTCMinutes();
|
||||
@@ -134,14 +174,21 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
this.seed = Math.floor(time / this.settings.change_frequency);
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбор случайного слова
|
||||
* @param {string} name
|
||||
* @param {StupidTitleWeightedVariants} variants
|
||||
* @return {string}
|
||||
* @private
|
||||
*/
|
||||
private selectRandom(
|
||||
name: string,
|
||||
variants: StupidTitleWeightedVariants
|
||||
name: string,
|
||||
variants: StupidTitleWeightedVariants,
|
||||
): string {
|
||||
const elements = Object.keys(variants);
|
||||
const totalWeight = elements.reduce(
|
||||
(sum, element) => sum + variants[element],
|
||||
0
|
||||
(sum, element) => sum + variants[element],
|
||||
0,
|
||||
);
|
||||
const randomWeight = this.prng(name, this.seed++, totalWeight);
|
||||
|
||||
@@ -153,12 +200,19 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error("Тебя быть тут не должно...");
|
||||
throw new Error('Тебя быть тут не должно...');
|
||||
}
|
||||
|
||||
/**
|
||||
* Выбор случайной фразы
|
||||
* @param {string} type
|
||||
* @param {boolean} gender
|
||||
* @return {StupidTitleWeightedVariants}
|
||||
* @private
|
||||
*/
|
||||
private buildVariants(
|
||||
type: string,
|
||||
gender: boolean
|
||||
type: string,
|
||||
gender: boolean,
|
||||
): StupidTitleWeightedVariants {
|
||||
const result: StupidTitleWeightedVariants = {};
|
||||
const variants: StupidTitleVariant = this.settings.variants[type];
|
||||
@@ -181,24 +235,27 @@ export class StupidTitleJoke extends Joke<StupidTitleJokeSettings> {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сделать первую буква слова заглавной
|
||||
* @param {string} str Слово
|
||||
* @return {string} Исправленное слово
|
||||
* @private
|
||||
*/
|
||||
private capitalizeFirst(str: string): string {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1);
|
||||
}
|
||||
|
||||
generatePhrase(name: string): string {
|
||||
const gender = this.resolveGender(name);
|
||||
const prhase = this.selectRandom(name, this.settings.schemas);
|
||||
|
||||
return this.capitalizeFirst(
|
||||
prhase.replace(/\{(.+?)\}/g, (_, type: string) => {
|
||||
const variants = this.buildVariants(type, gender);
|
||||
|
||||
return this.selectRandom(name, variants);
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Определение пола по имени.
|
||||
* @param {string} name Имя персонажа
|
||||
* @return {boolean | null} true, если мужской род; false, если женский род
|
||||
*/
|
||||
type GenderResolverFunction = (name: string) => (boolean | null);
|
||||
|
||||
/**
|
||||
* Класс настроек для шутки "Глупые статусы"
|
||||
*/
|
||||
export class StupidTitleJokeSettings implements JokeSettings {
|
||||
enabled: boolean = true;
|
||||
chance: number = 100;
|
||||
@@ -207,12 +264,13 @@ export class StupidTitleJokeSettings implements JokeSettings {
|
||||
* Определение пола по имени.
|
||||
* По умолчанию род устанавливается случайным образом
|
||||
*
|
||||
* Если установлено значение `null`, система попытается загрузить пол, установленный в настройках аккаунта. Если этот пол определить невозможно, то он будет выбран случайно. Эта настройка позволяет изменить это поведение, если ваш форум обладает ролевой системой, в которой пол определяется иным образом.
|
||||
*
|
||||
* @param name Имя персонажа
|
||||
* @returns true, если мужской род; false, если женский род
|
||||
* Если установлено значение `null`, система попытается загрузить пол,
|
||||
* установленный в настройках аккаунта. Если этот пол определить невозможно,
|
||||
* то он будет выбран случайно. Эта настройка позволяет изменить это
|
||||
* поведение, если ваш форум обладает ролевой системой, в которой пол
|
||||
* определяется иным образом.
|
||||
*/
|
||||
gender_resolver: Function | null = null;
|
||||
gender_resolver: GenderResolverFunction | null = null;
|
||||
|
||||
/**
|
||||
* Разрешить возможно оскорбительные варианты
|
||||
@@ -221,7 +279,8 @@ export class StupidTitleJokeSettings implements JokeSettings {
|
||||
|
||||
/**
|
||||
* Частота смены статусов (в минутах)
|
||||
* Установите значение 0, что бы обновление происходило при каждом обновлении страницы
|
||||
* Установите значение 0, что бы обновление происходило при
|
||||
* каждом обновлении страницы
|
||||
*/
|
||||
change_frequency: number = 5;
|
||||
|
||||
@@ -236,14 +295,14 @@ export class StupidTitleJokeSettings implements JokeSettings {
|
||||
* {p} - знак препинания
|
||||
*/
|
||||
schemas: StupidTitleWeightedVariants = {
|
||||
"{adj} {noun}{p}": 10,
|
||||
"{noun} {adj}{p}": 3,
|
||||
"{adj}, {adj} {noun}{p}": 10,
|
||||
"{adj} и очень {adj} {noun}{p}": 10,
|
||||
"{adj} {noun} {verb}{p}": 10,
|
||||
"{adj} {noun} {adv} {verb}{p}": 5,
|
||||
"{adj} {noun} {verb} {place}{p}": 5,
|
||||
"{adj} {noun} {adv} {verb} {place}{p}": 5,
|
||||
'{adj} {noun}{p}': 10,
|
||||
'{noun} {adj}{p}': 3,
|
||||
'{adj}, {adj} {noun}{p}': 10,
|
||||
'{adj} и очень {adj} {noun}{p}': 10,
|
||||
'{adj} {noun} {verb}{p}': 10,
|
||||
'{adj} {noun} {adv} {verb}{p}': 5,
|
||||
'{adj} {noun} {verb} {place}{p}': 5,
|
||||
'{adj} {noun} {adv} {verb} {place}{p}': 5,
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -257,13 +316,13 @@ export class StupidTitleJokeSettings implements JokeSettings {
|
||||
place: {},
|
||||
adv: {},
|
||||
p: {
|
||||
"": new StupidTitleSetting({ weight: 10 }),
|
||||
".": new StupidTitleSetting({ weight: 10 }),
|
||||
"...": new StupidTitleSetting({ weight: 5 }),
|
||||
"!": new StupidTitleSetting({ weight: 5 }),
|
||||
"!!!": new StupidTitleSetting({ weight: 2 }),
|
||||
"?": new StupidTitleSetting({ weight: 2 }),
|
||||
"?!": new StupidTitleSetting({ weight: 1 }),
|
||||
'': new StupidTitleSetting({weight: 15}),
|
||||
'.': new StupidTitleSetting({weight: 10}),
|
||||
'...': new StupidTitleSetting({weight: 5}),
|
||||
'!': new StupidTitleSetting({weight: 5}),
|
||||
'!!!': new StupidTitleSetting({weight: 2}),
|
||||
'?': new StupidTitleSetting({weight: 2}),
|
||||
'?!': new StupidTitleSetting({weight: 1}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -280,6 +339,16 @@ interface StupidTitleWeightedVariants {
|
||||
[key: string]: number;
|
||||
}
|
||||
|
||||
type StupidTitleSettingInitializer = {
|
||||
weight?: number;
|
||||
enabled?: boolean;
|
||||
rude?: boolean;
|
||||
gender?: boolean | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Класс настройки
|
||||
*/
|
||||
class StupidTitleSetting {
|
||||
weight: number = 10;
|
||||
|
||||
@@ -289,42 +358,62 @@ class StupidTitleSetting {
|
||||
|
||||
gender: boolean | null = null;
|
||||
|
||||
constructor(options: any = new Object()) {
|
||||
for (const iterator of Object.entries(options)) {
|
||||
if (iterator[0] in this) {
|
||||
(<any>this)[iterator[0]] = iterator[1];
|
||||
}
|
||||
}
|
||||
/**
|
||||
* Создание класса
|
||||
* @param {StupidTitleSettingInitializer} options
|
||||
*/
|
||||
constructor(options: StupidTitleSettingInitializer) {
|
||||
this.weight ??= options.weight;
|
||||
this.enabled ??= options.enabled;
|
||||
this.rude ??= options.rude;
|
||||
this.gender ??= options.gender;
|
||||
}
|
||||
}
|
||||
|
||||
export function BuildStupdiTitleVariant(
|
||||
gender: boolean | null,
|
||||
input: string
|
||||
/**
|
||||
* Метод создания списка слов
|
||||
* @param {boolean | null} gender
|
||||
* @param {string} input
|
||||
* @return {StupidTitleVariant}
|
||||
* @constructor
|
||||
*/
|
||||
export function BuildStupidTitleVariant(
|
||||
gender: boolean | null,
|
||||
input: string,
|
||||
): StupidTitleVariant {
|
||||
const result: StupidTitleVariant = {};
|
||||
const words = input.split(",").map((word) => word.trim());
|
||||
const words = input.split(',').map((word) => word.trim());
|
||||
|
||||
words.forEach((word) => {
|
||||
const clean_word = word.replace(/[^А-ЯЁа-яёA-Za-z\- ]/g, "");
|
||||
const cleanWord = word.replace(/[^А-ЯЁа-яёA-Za-z\- ]/g, '');
|
||||
|
||||
if (clean_word === "") {
|
||||
if (cleanWord === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
result[clean_word] = new StupidTitleSetting({
|
||||
result[cleanWord] = new StupidTitleSetting({
|
||||
gender,
|
||||
rude: word.indexOf("$") >= 0,
|
||||
enabled: word.indexOf("!") < 0,
|
||||
rude: word.indexOf('$') >= 0,
|
||||
enabled: word.indexOf('!') < 0,
|
||||
weight:
|
||||
10 *
|
||||
(word.indexOf("$") >= 0 ? 0.5 : 1) *
|
||||
(word.indexOf("%") >= 0 ? 0.5 : 1) *
|
||||
(word.indexOf("^") >= 0 ? 2 : 1),
|
||||
10 *
|
||||
(word.indexOf('$') >= 0 ? 0.5 : 1) *
|
||||
(word.indexOf('%') >= 0 ? 0.5 : 1) *
|
||||
(word.indexOf('^') >= 0 ? 2 : 1),
|
||||
});
|
||||
});
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
(window as any).BuildStupdiTitleVariant = BuildStupdiTitleVariant;
|
||||
declare global {
|
||||
interface Window {
|
||||
BuildStupidTitleVariant(
|
||||
gender: boolean | null,
|
||||
input: string,
|
||||
): StupidTitleVariant;
|
||||
}
|
||||
}
|
||||
|
||||
window.BuildStupidTitleVariant = BuildStupidTitleVariant;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user