@zoodogood/utils 1.0.8-change.941 → 1.1.0-change.1043

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zoodogood/utils",
3
3
  "type": "module",
4
- "version": "1.0.8-change.941",
4
+ "version": "1.1.0-change.1043",
5
5
  "description": "",
6
6
  "main": "lib/index.js",
7
7
  "types": "lib/index.d.ts",
package/readme.md CHANGED
@@ -10,4 +10,4 @@ export { ending } from '@zoodogood/utils/primitives';
10
10
  [NPM](https://www.npmjs.com/package/@zoodogood/utils)
11
11
 
12
12
  #### From developer:
13
- (Wa) Use only documented functions that are not marked "Unstable". Thanks.
13
+ (Warning) Use only documented functions that are not marked "Unstable". Thanks.
@@ -1,10 +0,0 @@
1
- export type APIBaseButton = import("discord-api-types/v10").APIButtonComponentBase<any>;
2
- /**
3
- * @typedef {import("discord-api-types/v10").APIButtonComponentBase} APIBaseButton
4
- */
5
- /**
6
- *
7
- * @param {APIBaseButton} resolable
8
- */
9
- export function justButtonComponents(resolable: import("discord-api-types/v10").APIButtonComponentBase<any>): any;
10
- export function justSendMessage(target: any, options: any): Promise<any>;
@@ -1,48 +0,0 @@
1
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
- return new (P || (P = Promise))(function (resolve, reject) {
4
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
- step((generator = generator.apply(thisArg, _arguments || [])).next());
8
- });
9
- };
10
- import { BaseInteraction, ButtonStyle, ComponentType } from "discord.js";
11
- import { SimplifyComponents, CreateMessage } from "./simplify.js";
12
- const DEFAULTS_FOR_BUTTON = {
13
- type: ComponentType.Button,
14
- style: ButtonStyle.Secondary,
15
- };
16
- /**
17
- * @typedef {import("discord-api-types/v10").APIButtonComponentBase} APIBaseButton
18
- */
19
- /**
20
- *
21
- * @param {APIBaseButton} resolable
22
- */
23
- function justButtonComponents(resolable) {
24
- const buttons = resolable.map((data, i) => (Object.assign(Object.assign(Object.assign({}, DEFAULTS_FOR_BUTTON), { customId: `button.${i + 1}` }), data)));
25
- return SimplifyComponents(buttons);
26
- }
27
- function justSendMessage(target, options) {
28
- return __awaiter(this, void 0, void 0, function* () {
29
- const messagePayload = CreateMessage(options);
30
- const message = target instanceof BaseInteraction
31
- ? yield (options.edit
32
- ? target.replied
33
- ? target.editReply(messagePayload)
34
- : target.update(messagePayload)
35
- : target.reply(messagePayload))
36
- : yield (options.edit
37
- ? target.edit(messagePayload)
38
- : target.send(messagePayload));
39
- if (options.delete) {
40
- setTimeout(() => message.delete(), options.delete);
41
- }
42
- if (options.reactions) {
43
- options.reactions.filter(Boolean).forEach((react) => message.react(react));
44
- }
45
- return message;
46
- });
47
- }
48
- export { justButtonComponents, justSendMessage };
@@ -1,2 +0,0 @@
1
- export * from "./helpers.js";
2
- export * from "./simplify.js";
@@ -1,2 +0,0 @@
1
- export * from "./helpers.js";
2
- export * from "./simplify.js";
@@ -1,54 +0,0 @@
1
- /**
2
- * Create a message object for Discord.
3
- *
4
- * @param {Object} params = Parameters for creating the message.
5
- * @param {string} [params.content] - The message content.
6
- * @param {string} [params.title] - The title of the embed.
7
- * @param {string} [params.url] - The URL of the embed.
8
- * @param {Object} [params.author] - The author of the embed.
9
- * @param {string} [params.thumbnail] - The thumbnail URL of the embed.
10
- * @param {string} [params.description] - The description of the embed.
11
- * @param {string} [params.color] - The color of the embed.
12
- * @param {Object[]} [params.fields] - The fields of the embed.
13
- * @param {string} [params.image] - The image URL of the embed.
14
- * @param {string} [params.video] - The video URL of the embed.
15
- * @param {Object} [params.footer] - The footer of the embed.
16
- * @param {string} [params.timestamp] - The timestamp of the embed.
17
- * @param {boolean} [params.ephemeral] - Whether the message should be ephemeral.
18
- * @param {boolean} [params.fetchReply] - Whether to fetch the message reply.
19
- * @param {Object[] | Object} [params.components] - The message components.
20
- * @param {Object[] | Object[]} [params.files] - The message files.
21
- * @param {string} [params.reference] - The message reference.
22
- * @returns {Object} - The message object.
23
- */
24
- export function CreateMessage({ content, title, url, author, thumbnail, description, color, fields, image, video, footer, timestamp, ephemeral, fetchReply, components, files, reference, }: {
25
- content?: string | undefined;
26
- title?: string | undefined;
27
- url?: string | undefined;
28
- author?: Object | undefined;
29
- thumbnail?: string | undefined;
30
- description?: string | undefined;
31
- color?: string | undefined;
32
- fields?: Object[] | undefined;
33
- image?: string | undefined;
34
- video?: string | undefined;
35
- footer?: Object | undefined;
36
- timestamp?: string | undefined;
37
- ephemeral?: boolean | undefined;
38
- fetchReply?: boolean | undefined;
39
- components?: Object | Object[] | undefined;
40
- files?: Object[] | undefined;
41
- reference?: string | undefined;
42
- }): Object;
43
- export function CreateModal({ title, customId, components }: {
44
- title: any;
45
- customId: any;
46
- components: any;
47
- }): import("discord.js").APIModalInteractionResponseCallbackData;
48
- export function SimplifyComponents(data: any): any;
49
- /**
50
- *
51
- * @param {*} embed
52
- * @returns {boolean}
53
- */
54
- export function isEmptyEmbed(embed: any): boolean;
@@ -1,116 +0,0 @@
1
- import { EmbedBuilder, ModalBuilder, resolveColor, ActionRow, } from "discord.js";
2
- import { ComponentType } from "discord-api-types/v10";
3
- /**
4
- *
5
- * @param {*} embed
6
- * @returns {boolean}
7
- */
8
- function isEmptyEmbed(embed) {
9
- const DEFAULT_PROPERTIES = {
10
- title: undefined,
11
- author: undefined,
12
- thumbnail: undefined,
13
- description: undefined,
14
- fields: undefined,
15
- image: undefined,
16
- footer: undefined,
17
- timestamp: undefined,
18
- video: undefined,
19
- };
20
- // in isEmptyEmbed context is a good compare
21
- const isEqualDefault = (key) => String(embed[key]) === String(DEFAULT_PROPERTIES[key]);
22
- const isEveryPropertyDefault = Object.keys(DEFAULT_PROPERTIES).every(isEqualDefault);
23
- return isEveryPropertyDefault;
24
- }
25
- /**
26
- * Create a message object for Discord.
27
- *
28
- * @param {Object} params = Parameters for creating the message.
29
- * @param {string} [params.content] - The message content.
30
- * @param {string} [params.title] - The title of the embed.
31
- * @param {string} [params.url] - The URL of the embed.
32
- * @param {Object} [params.author] - The author of the embed.
33
- * @param {string} [params.thumbnail] - The thumbnail URL of the embed.
34
- * @param {string} [params.description] - The description of the embed.
35
- * @param {string} [params.color] - The color of the embed.
36
- * @param {Object[]} [params.fields] - The fields of the embed.
37
- * @param {string} [params.image] - The image URL of the embed.
38
- * @param {string} [params.video] - The video URL of the embed.
39
- * @param {Object} [params.footer] - The footer of the embed.
40
- * @param {string} [params.timestamp] - The timestamp of the embed.
41
- * @param {boolean} [params.ephemeral] - Whether the message should be ephemeral.
42
- * @param {boolean} [params.fetchReply] - Whether to fetch the message reply.
43
- * @param {Object[] | Object} [params.components] - The message components.
44
- * @param {Object[] | Object[]} [params.files] - The message files.
45
- * @param {string} [params.reference] - The message reference.
46
- * @returns {Object} - The message object.
47
- */
48
- function CreateMessage({ content, title, url, author, thumbnail, description, color, fields, image, video, footer, timestamp, ephemeral, fetchReply, components, files, reference, }) {
49
- const message = {};
50
- thumbnail && (thumbnail = { url: thumbnail });
51
- image && (image = { url: image });
52
- video && (video = { url: video });
53
- color = resolveColor(color !== null && color !== void 0 ? color : "Random");
54
- const embed = new EmbedBuilder({
55
- title,
56
- url,
57
- author,
58
- thumbnail,
59
- description,
60
- color,
61
- fields,
62
- image,
63
- video,
64
- footer,
65
- timestamp,
66
- });
67
- if (!isEmptyEmbed(embed.data)) {
68
- message.embeds = [embed];
69
- }
70
- if (files) {
71
- message.files = files;
72
- }
73
- if (reference)
74
- message.reply = {
75
- messageReference: reference,
76
- };
77
- message.components = components ? SimplifyComponents(components) : null;
78
- message.content = content;
79
- message.ephemeral = ephemeral;
80
- message.fetchReply = fetchReply;
81
- return message;
82
- }
83
- function CreateModal({ title, customId, components }) {
84
- components = SimplifyComponents(components);
85
- return new ModalBuilder({ title, customId, components }).toJSON();
86
- }
87
- function SimplifyComponents(data) {
88
- if (data instanceof Array && data.length === 0)
89
- return [];
90
- const isComponent = (component) => "type" in component && component.type !== ComponentType.ActionRow;
91
- const isActionRow = (component) => (component instanceof Array && isComponent(component.at(0))) ||
92
- component instanceof ActionRow;
93
- const isComponents = (component) => component instanceof Array && isActionRow(component.at(0));
94
- const argumentType = [
95
- isComponent(data),
96
- isActionRow(data),
97
- isComponents(data),
98
- ].findIndex(Boolean);
99
- if (argumentType === -1)
100
- throw new TypeError("expected component");
101
- const wrapToArray = (component) => [component];
102
- const arrayToActionRow = (componentsArray) => {
103
- const isActionRow = "type" in componentsArray &&
104
- componentsArray.type === ComponentType.ActionRow;
105
- if (isActionRow)
106
- return componentsArray;
107
- return { type: ComponentType.ActionRow, components: componentsArray };
108
- };
109
- if (argumentType <= 0)
110
- data = wrapToArray(data);
111
- if (argumentType <= 1)
112
- data = wrapToArray(data);
113
- data = data.map(arrayToActionRow);
114
- return data;
115
- }
116
- export { CreateMessage, CreateModal, SimplifyComponents, isEmptyEmbed };
package/lib/index.d.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from './primitives/mod.js';
2
- export * from './objectives/mod.js';
@@ -1,23 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type { ChildProcessWithoutNullStreams } from "child_process";
3
- import EventsEmitter from "events";
4
- interface IContext {
5
- exitter: {
6
- resolve: any;
7
- reject: any;
8
- };
9
- whenEnd: Promise<unknown>;
10
- child: ChildProcessWithoutNullStreams;
11
- emitter: EventsEmitter;
12
- outString: string;
13
- }
14
- interface IParams {
15
- root: string;
16
- logger?: boolean;
17
- }
18
- declare const _default: ({ root, logger }: IParams) => {
19
- run: (command: string, params: string[]) => IContext;
20
- info: (log: string) => void;
21
- _npm: string;
22
- };
23
- export default _default;
@@ -1,98 +0,0 @@
1
- import { spawn } from "child_process";
2
- import EventsEmitter from "events";
3
- export default ({ root, logger = false }) => {
4
- // Solve problem: https://stackoverflow.com/questions/43230346/error-spawn-npm-enoent
5
- const _npm = process.platform === "win32" ? "npm.cmd" : "npm";
6
- const EventsCallbacks = [
7
- {
8
- key: "stdoutError",
9
- callback({ exitter }, error) {
10
- logger && info(`Error: ${error.message}`);
11
- exitter.reject(error);
12
- },
13
- },
14
- {
15
- key: "stderrError",
16
- callback({ exitter }, error) {
17
- logger && info(`Error: ${error.message}`);
18
- exitter.reject(error);
19
- },
20
- },
21
- {
22
- key: "stdoutData",
23
- callback(context, data) {
24
- const content = String(data);
25
- context.emitter.emit("data", content);
26
- context.outString = context.outString.concat(content);
27
- logger && console.info(content);
28
- },
29
- },
30
- {
31
- key: "stderrData",
32
- callback(context, data) {
33
- const content = String(data);
34
- context.emitter.emit("data", content);
35
- context.outString = context.outString.concat(content);
36
- logger && console.info(content);
37
- },
38
- },
39
- {
40
- key: "message",
41
- callback(_context, data) {
42
- logger && console.info(data.toString());
43
- },
44
- },
45
- {
46
- key: "exit",
47
- callback({ exitter, outString }) {
48
- exitter.resolve(outString);
49
- },
50
- },
51
- {
52
- key: "error",
53
- callback({ exitter }, error) {
54
- logger && info(`Error: ${error.message}`);
55
- exitter.reject(error);
56
- },
57
- },
58
- ];
59
- const info = (log) => console.info(`\x1b[1m${log}\x1b[22m`);
60
- const run = (command, params) => {
61
- const child = spawn(command, params, { cwd: root });
62
- const exitter = { resolve: null, reject: null };
63
- const promise = new Promise((resolve, reject) => Object.assign(exitter, { resolve, reject }));
64
- const emitter = new EventsEmitter();
65
- const outString = "";
66
- const context = {
67
- exitter,
68
- whenEnd: promise,
69
- child,
70
- emitter,
71
- outString,
72
- };
73
- const events = Object.fromEntries(EventsCallbacks.map(({ callback, key }) => [
74
- key,
75
- callback.bind(null, context),
76
- ]));
77
- (() => {
78
- child.stdout.on("error", events.stdoutError);
79
- child.stderr.on("error", events.stderrError);
80
- child.stdout.on("data", events.stdoutData);
81
- child.stderr.on("data", events.stderrData);
82
- child.on("error", events.error);
83
- child.on("message", events.message);
84
- child.on("exit", events.exit);
85
- })();
86
- promise.finally(() => {
87
- child.stdout.removeListener("error", events.stdoutError);
88
- child.stderr.removeListener("error", events.stderrError);
89
- child.stdout.removeListener("data", events.stdoutData);
90
- child.stderr.removeListener("data", events.stderrData);
91
- child.removeListener("error", events.error);
92
- child.removeListener("message", events.message);
93
- child.removeListener("exit", events.exit);
94
- });
95
- return context;
96
- };
97
- return { run, info, _npm };
98
- };
@@ -1 +0,0 @@
1
- export { default as getChildProcessUtils } from './getChildProcessUtils.js';
package/lib/nodejs/mod.js DELETED
@@ -1 +0,0 @@
1
- export { default as getChildProcessUtils } from './getChildProcessUtils.js';
@@ -1,25 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- interface ICustomCollectorOptions {
3
- target: Required<{
4
- removeListener: CallableFunction;
5
- on: CallableFunction;
6
- }>;
7
- event: string;
8
- filter?: Function;
9
- time: number;
10
- }
11
- declare class CustomCollector {
12
- #private;
13
- timeoutId?: NodeJS.Timeout;
14
- target: ICustomCollectorOptions["target"];
15
- event: ICustomCollectorOptions["event"];
16
- filter: ICustomCollectorOptions["filter"];
17
- time: ICustomCollectorOptions["time"];
18
- constructor({ target, event, filter, time }: ICustomCollectorOptions);
19
- setCallback(callback: CallableFunction): void;
20
- handle(handler: CallableFunction): void;
21
- end(): void;
22
- removeTimeout(): void;
23
- setTimeout(ms: number): void;
24
- }
25
- export { CustomCollector };
@@ -1,59 +0,0 @@
1
- var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {
2
- if (kind === "m") throw new TypeError("Private method is not writable");
3
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
4
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
5
- return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;
6
- };
7
- var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
8
- if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
9
- if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
10
- return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
11
- };
12
- var _CustomCollector_callback;
13
- class CustomCollector {
14
- constructor({ target, event, filter, time = 0 }) {
15
- _CustomCollector_callback.set(this, void 0);
16
- if ("on" in target === false) {
17
- throw new Error("Target must be similar to EventEmitter.prototype — target haven't method 'on'");
18
- }
19
- this.target = target;
20
- this.event = event;
21
- this.filter = filter;
22
- this.time = time;
23
- }
24
- setCallback(callback) {
25
- const handler = (...params) => {
26
- const passed = !this.filter || this.filter(params);
27
- if (!!passed === true) {
28
- // @ts-ignore
29
- callback.apply(this, params);
30
- }
31
- };
32
- this.handle(handler);
33
- }
34
- handle(handler) {
35
- this.end();
36
- __classPrivateFieldSet(this, _CustomCollector_callback, handler, "f");
37
- this.target.on(this.event, __classPrivateFieldGet(this, _CustomCollector_callback, "f"));
38
- if (this.time > 0) {
39
- this.setTimeout(this.time);
40
- }
41
- }
42
- end() {
43
- if (this.timeoutId) {
44
- this.removeTimeout();
45
- }
46
- if (__classPrivateFieldGet(this, _CustomCollector_callback, "f")) {
47
- this.target.removeListener(this.event, __classPrivateFieldGet(this, _CustomCollector_callback, "f"));
48
- }
49
- }
50
- removeTimeout() {
51
- clearTimeout(this.timeoutId);
52
- }
53
- setTimeout(ms) {
54
- const callback = this.end.bind(this);
55
- this.timeoutId = setTimeout(callback, ms);
56
- }
57
- }
58
- _CustomCollector_callback = new WeakMap();
59
- export { CustomCollector };
@@ -1,23 +0,0 @@
1
- interface IMethodsOptions {
2
- defaultValue?: any;
3
- allowSetFunctions?: boolean;
4
- }
5
- export declare class DotNotatedInterface {
6
- target: Record<string, unknown>;
7
- constructor(target: DotNotatedInterface["target"]);
8
- getItem<T>(key: string, options?: IMethodsOptions): T | null;
9
- setItem<T>(key: string, value: CallableFunction, options?: IMethodsOptions): T;
10
- hasItem(key: string, options?: IMethodsOptions): boolean;
11
- removeItem(key: string, options?: IMethodsOptions): boolean;
12
- getParentAndlastSegmentByNotatedKey(key: string, { needFillIfParentNotExists }: {
13
- needFillIfParentNotExists?: boolean | undefined;
14
- }): {
15
- parent: object | null;
16
- lastSegment: string;
17
- };
18
- fillIsNotExists({ parent, segment, }: {
19
- parent: {};
20
- segment: string;
21
- }): string;
22
- }
23
- export {};
@@ -1,60 +0,0 @@
1
- export class DotNotatedInterface {
2
- constructor(target) {
3
- this.target = target;
4
- }
5
- getItem(key, options = {}) {
6
- var _a;
7
- const { parent, lastSegment } = this.getParentAndlastSegmentByNotatedKey(key, { needFillIfParentNotExists: false });
8
- if (!parent || lastSegment in parent === false) {
9
- return (_a = options.defaultValue) !== null && _a !== void 0 ? _a : null;
10
- }
11
- // @ts-ignore
12
- return parent[lastSegment];
13
- }
14
- setItem(key, value, options = {}) {
15
- if (typeof value === "function" && !options.allowSetFunctions) {
16
- value = value(this.getItem(key, options));
17
- }
18
- const { parent, lastSegment } = this.getParentAndlastSegmentByNotatedKey(key, { needFillIfParentNotExists: true });
19
- // @ts-ignore
20
- return (parent[lastSegment] = value);
21
- }
22
- hasItem(key, options = {}) {
23
- const { parent, lastSegment } = this.getParentAndlastSegmentByNotatedKey(key, { needFillIfParentNotExists: false });
24
- if (parent === null) {
25
- return false;
26
- }
27
- return lastSegment in parent;
28
- }
29
- removeItem(key, options = {}) {
30
- const { parent, lastSegment } = this.getParentAndlastSegmentByNotatedKey(key, { needFillIfParentNotExists: false });
31
- if (!parent) {
32
- return false;
33
- }
34
- // @ts-ignore
35
- return delete parent[lastSegment];
36
- }
37
- getParentAndlastSegmentByNotatedKey(key, { needFillIfParentNotExists = false }) {
38
- const pathSegments = key.split(".");
39
- if (!pathSegments.length) {
40
- throw new Error("Empty path to property");
41
- }
42
- let parent = this.target;
43
- for (let segment of pathSegments.slice(0, -1)) {
44
- needFillIfParentNotExists &&
45
- (segment = this.fillIsNotExists({ parent, segment }));
46
- if (parent[segment] === undefined) {
47
- return { parent: null, lastSegment: segment };
48
- }
49
- parent = parent[segment];
50
- }
51
- return { parent, lastSegment: pathSegments.at(-1) };
52
- }
53
- fillIsNotExists({ parent, segment, }) {
54
- if (segment in parent === false) {
55
- // @ts-ignore
56
- parent[segment] = {};
57
- }
58
- return segment;
59
- }
60
- }
@@ -1,16 +0,0 @@
1
- interface IGlitchTextOptions {
2
- step?: number;
3
- random?: boolean;
4
- maximum?: number;
5
- }
6
- declare class GlitchText {
7
- from: string;
8
- to: string;
9
- step: number;
10
- random: boolean;
11
- maximum: number;
12
- [Symbol.iterator]: () => Generator<string>;
13
- constructor(from?: string, to?: string, { step, random, maximum }?: IGlitchTextOptions);
14
- iteratorFunction(): Generator<string, void, unknown>;
15
- }
16
- export { GlitchText };
@@ -1,50 +0,0 @@
1
- import { getRandomNumberInRange } from "./getRandomNumberInRange.js";
2
- class GlitchText {
3
- constructor(from = "", to = "hello, world", { step = 15, random = false, maximum = 100 } = {}) {
4
- this.from = from;
5
- this.to = to;
6
- this.step = step;
7
- this.random = random;
8
- this.maximum = maximum;
9
- this[Symbol.iterator] = this.iteratorFunction;
10
- }
11
- *iteratorFunction() {
12
- const word = [...this.from];
13
- const target = this.to;
14
- const MIN = 20;
15
- const MAX = 40;
16
- while (word.length !== target.length) {
17
- if (word.length > target.length)
18
- word.pop();
19
- if (word.length < target.length)
20
- word.push(String.fromCharCode(~~(Math.random() * 50)));
21
- word.forEach((_, index, array) => array[index] = String.fromCharCode(getRandomNumberInRange({ min: MIN, max: MAX })));
22
- yield word.join("");
23
- }
24
- if (this.maximum)
25
- for (const index in word) {
26
- const charCode = word[index].charCodeAt(0);
27
- const targetCode = target[index].charCodeAt(0);
28
- if (Math.abs(charCode - targetCode) > this.maximum)
29
- word[index] = String.fromCharCode(charCode > targetCode ?
30
- targetCode + this.maximum :
31
- targetCode - this.maximum);
32
- }
33
- ;
34
- while (word.join("") !== target) {
35
- word.forEach((letter, i) => {
36
- if (letter === target[i])
37
- return;
38
- const charCode = letter.charCodeAt(0), targetCode = target[i].charCodeAt(0);
39
- const isUpper = targetCode > charCode;
40
- let step = Math.min(Math.abs(targetCode - charCode), this.step);
41
- if (this.random)
42
- step *= Math.random() * 2;
43
- word[i] = String.fromCharCode(isUpper ? charCode + step : charCode - step);
44
- });
45
- yield word.join("");
46
- }
47
- return;
48
- }
49
- }
50
- export { GlitchText };
@@ -1,7 +0,0 @@
1
- interface IParams {
2
- needPop?: boolean;
3
- associatedWeights?: number[];
4
- }
5
- export declare function getRandomElementIndexInWeights(weights: NonNullable<IParams["associatedWeights"]>): number | never;
6
- export declare function getRandomElementFromArray<T>(array: T[], { needPop, associatedWeights }?: IParams): T;
7
- export {};
@@ -1,24 +0,0 @@
1
- import { getRandomNumberInRange } from "./getRandomNumberInRange.js";
2
- export function getRandomElementIndexInWeights(weights) {
3
- if (weights.length < 1) {
4
- new Error("Invalid array length");
5
- }
6
- let previousLimit = 0;
7
- const thresholds = weights.map((weight) => (previousLimit += weight));
8
- const lotterySecretNumber = Math.random() * thresholds.at(-1);
9
- return thresholds.findIndex((threshold) => threshold >= lotterySecretNumber);
10
- }
11
- export function getRandomElementFromArray(array, { needPop, associatedWeights } = {}) {
12
- if (associatedWeights && associatedWeights.length !== array.length) {
13
- throw new Error("Incorrectly passed argument associatedWeights: The length of the associatedWeights must exactly match the length of the weights array");
14
- }
15
- const index = associatedWeights
16
- ? getRandomElementIndexInWeights(associatedWeights)
17
- : getRandomNumberInRange({ max: array.length });
18
- const input = array[index];
19
- if (needPop) {
20
- array.splice(index, 1);
21
- associatedWeights === null || associatedWeights === void 0 ? void 0 : associatedWeights.splice(index, 1);
22
- }
23
- return input;
24
- }
@@ -1,7 +0,0 @@
1
- interface IGetRandomValueOptions {
2
- min?: number;
3
- max: number;
4
- needRound?: boolean;
5
- }
6
- declare function getRandomNumberInRange({ min, max, needRound }: IGetRandomValueOptions): number;
7
- export { getRandomNumberInRange };
@@ -1,8 +0,0 @@
1
- function getRandomNumberInRange({ min = 0, max, needRound = true }) {
2
- let value = Math.random() * (max - min + Number(needRound)) + min;
3
- if (needRound) {
4
- value = Math.floor(value);
5
- }
6
- return value;
7
- }
8
- export { getRandomNumberInRange };
@@ -1,7 +0,0 @@
1
- interface IGetRandomValueOptions {
2
- min?: number;
3
- max: number;
4
- round?: boolean;
5
- }
6
- declare function getRandomValue({ min, max, round }: IGetRandomValueOptions): number;
7
- export { getRandomValue };
@@ -1,8 +0,0 @@
1
- function getRandomValue({ min = 0, max, round = true }) {
2
- let value = Math.random() * (max - min + Number(round)) + min;
3
- if (round) {
4
- value = Math.floor(value);
5
- }
6
- return value;
7
- }
8
- export { getRandomValue };
@@ -1,10 +0,0 @@
1
- export * from './CustomCollector.js';
2
- export * from './GlitchText.js';
3
- export * from './getRandomNumberInRange.js';
4
- export * from './rangeToArray.js';
5
- export * from './getRandomElementFromArray.js';
6
- export * from './DotNotatedInterface.js';
7
- declare function omit(object: Object, filter: CallableFunction): {
8
- [k: string]: any;
9
- };
10
- export { omit };
@@ -1,12 +0,0 @@
1
- export * from './CustomCollector.js';
2
- export * from './GlitchText.js';
3
- export * from './getRandomNumberInRange.js';
4
- export * from './rangeToArray.js';
5
- export * from './getRandomElementFromArray.js';
6
- export * from './DotNotatedInterface.js';
7
- function omit(object, filter) {
8
- const entries = Object.entries(object)
9
- .filter(([key, value], i) => filter(key, value, i));
10
- return Object.fromEntries(entries);
11
- }
12
- export { omit };
@@ -1 +0,0 @@
1
- export declare function rangeToArray([min, max]: [number, number]): number | number[];
@@ -1,6 +0,0 @@
1
- export function rangeToArray([min, max]) {
2
- if (isNaN(min) || isNaN(max)) {
3
- return NaN;
4
- }
5
- return [...new Array(max - min + 1)].map((_, index) => index + min);
6
- }
@@ -1,71 +0,0 @@
1
- interface ITextTableGeneratorContext {
2
- content: string;
3
- metadata: IContextMetadata;
4
- currentRow: number;
5
- }
6
- interface IContextMetadata {
7
- columns?: {
8
- largestLength: number;
9
- }[];
10
- tableWidth?: number;
11
- separatorsIndexesInRow?: number[];
12
- }
13
- declare enum CellAlignEnum {
14
- Left = 0,
15
- Right = 1,
16
- Center = 2
17
- }
18
- interface ICellOptions {
19
- gapLeft: number;
20
- gapRight: number;
21
- align: CellAlignEnum;
22
- removeNextSeparator?: boolean;
23
- }
24
- interface ITableCell {
25
- value: string;
26
- options: ICellOptions;
27
- }
28
- type TCellSetSymbolCallback = (context: ITextTableGeneratorContext, index: number) => string;
29
- interface ICellBuilderOptions {
30
- minWidth?: number;
31
- maxWidth?: number;
32
- }
33
- interface ITableOptions {
34
- borderLeft: null | TCellSetSymbolCallback;
35
- borderRight: null | TCellSetSymbolCallback;
36
- borderTop: null | TCellSetSymbolCallback;
37
- borderBottom: null | TCellSetSymbolCallback;
38
- separator: string;
39
- }
40
- declare enum BorderDirectionEnum {
41
- BorderLeft = 0,
42
- BorderRight = 1,
43
- BorderTop = 2,
44
- BorderBottom = 3
45
- }
46
- declare enum SpecialRowTypeEnum {
47
- Default = 0,
48
- Display = 1
49
- }
50
- interface ITableSpecialDisplayRow {
51
- type: SpecialRowTypeEnum.Display;
52
- display: TCellSetSymbolCallback;
53
- }
54
- type TTableRow = ITableCell[] | ITableSpecialDisplayRow;
55
- declare class TextTableBuilder {
56
- rows: TTableRow[];
57
- protected options: ITableOptions;
58
- setBorderOptions(callback?: TCellSetSymbolCallback, directions?: BorderDirectionEnum[]): this;
59
- addRowWithElements(elements: ITableCell["value"][], optionsForEveryElement?: Partial<ICellOptions>, useOnAddingOptions?: ICellBuilderOptions): this;
60
- addMultilineRowWithElements(elements: ITableCell["value"][], optionsForEveryElement?: Partial<ICellOptions>, useOnAddingOptions?: ICellBuilderOptions): this;
61
- addEmptyRow(): this;
62
- addRowSeparator(setSymbol?: TCellSetSymbolCallback): this;
63
- addCellAtRow(rowIndex: number, cellValue: ITableCell["value"], cellOptions: ICellOptions, useOnAddingOptions: ICellBuilderOptions): this;
64
- private pushCellToArray;
65
- private pushRowToTable;
66
- generateTextContent(): string;
67
- addRowWithUnwrappedCells(cells: ITableCell[], useOnAddingOptions?: ICellBuilderOptions): this;
68
- }
69
- export { TextTableBuilder };
70
- export { SpecialRowTypeEnum, CellAlignEnum, BorderDirectionEnum };
71
- export type { ICellOptions, IContextMetadata, ITableCell, ITableOptions, ITextTableGeneratorContext, TTableRow, };
@@ -1,319 +0,0 @@
1
- function getRowType(row) {
2
- if ("type" in row === false) {
3
- return SpecialRowTypeEnum.Default;
4
- }
5
- return row.type;
6
- }
7
- function isCell(target) {
8
- if (!target) {
9
- return false;
10
- }
11
- return "value" in target && "options" in target;
12
- }
13
- function emptyCell() {
14
- return {
15
- value: "",
16
- options: DEFAULT_CELL_OPTIONS,
17
- };
18
- }
19
- function addPaddingByCellAlign(original, totalForAdd, align) {
20
- const addidableGapLeft = align === CellAlignEnum.Right
21
- ? totalForAdd
22
- : align === CellAlignEnum.Center
23
- ? Math.floor(totalForAdd / 2)
24
- : 0;
25
- const addidableGapRight = align === CellAlignEnum.Left
26
- ? totalForAdd
27
- : align === CellAlignEnum.Center
28
- ? Math.ceil(totalForAdd / 2)
29
- : 0;
30
- return `${" ".repeat(addidableGapLeft)}${original}${" ".repeat(addidableGapRight)}`;
31
- }
32
- function changeContentSetCellMinWidth(cell, minWidth) {
33
- const currentMin = calculateCellMinWidth(cell);
34
- if (minWidth <= currentMin) {
35
- return cell;
36
- }
37
- const { value, options: { align }, } = cell;
38
- const lack = minWidth - currentMin;
39
- cell.value = addPaddingByCellAlign(value, lack, align);
40
- return cell;
41
- }
42
- function changeContentSetCellMaxWidth(cell, maxWidth) {
43
- const current = calculateCellMinWidth(cell);
44
- if (maxWidth >= current) {
45
- return cell;
46
- }
47
- let overage = current - maxWidth;
48
- const gapDirection = cell.options.align === CellAlignEnum.Left ? "gapRight" : "gapLeft";
49
- if (cell.options[gapDirection] > 1) {
50
- cell.options[gapDirection]--;
51
- overage--;
52
- if (overage === 0) {
53
- return;
54
- }
55
- }
56
- const suffix = "..";
57
- const sliced = cell.value.slice(0, -(overage + suffix.length));
58
- cell.value = sliced + suffix;
59
- return cell;
60
- }
61
- function calculateCellMinWidth(cell) {
62
- const { gapLeft, gapRight } = cell.options;
63
- return cell.value.length + gapLeft + gapRight;
64
- }
65
- class TextTableGenerator {
66
- constructor(rows, options) {
67
- this.data = [];
68
- this.context = {
69
- content: "",
70
- metadata: {},
71
- currentRow: 0,
72
- };
73
- this.data = rows;
74
- this.options = options;
75
- this.parseMetadata();
76
- }
77
- generateTextContent() {
78
- const context = this.context;
79
- if (this.options.borderTop !== null) {
80
- context.content += this.drawBlockBorder(BorderDirectionEnum.BorderTop);
81
- context.content += "\n";
82
- }
83
- for (const row of this.data) {
84
- context.currentRow = this.data.indexOf(row);
85
- context.content += this.drawRow(row);
86
- context.content += "\n";
87
- }
88
- if (this.options.borderBottom !== null) {
89
- context.content += this.drawBlockBorder(BorderDirectionEnum.BorderBottom);
90
- }
91
- return context.content;
92
- }
93
- getColumns() {
94
- const columns = [];
95
- const rows = this.data;
96
- const largestCellsCount = Math.max(...rows
97
- .filter((row) => getRowType(row) === SpecialRowTypeEnum.Default)
98
- .map((row) => row.length));
99
- for (let index = 0; index < largestCellsCount; index++) {
100
- const column = rows.map((row) => {
101
- var _a;
102
- return getRowType(row) === SpecialRowTypeEnum.Default
103
- ? (_a = row.at(index)) !== null && _a !== void 0 ? _a : null
104
- : { row };
105
- });
106
- columns.push(column);
107
- }
108
- return columns;
109
- }
110
- parseMetadata() {
111
- const metadata = this.context.metadata;
112
- const columns = this.getColumns();
113
- const columnsMetadata = columns.map((column) => ({
114
- largestLength: Math.max(...column.map((element) => isCell(element) ? calculateCellMinWidth(element) : 0)),
115
- }));
116
- metadata.columns = columnsMetadata;
117
- metadata.tableWidth = this.calculateTableWidth();
118
- metadata.separatorsIndexesInRow = (() => {
119
- const indexes = [];
120
- let current = 0;
121
- if (!!this.options.borderLeft) {
122
- indexes.push(current);
123
- }
124
- for (const { largestLength } of columnsMetadata) {
125
- current += largestLength + 1;
126
- indexes.push(current);
127
- }
128
- if (!this.options.borderRight) {
129
- indexes.pop();
130
- }
131
- return indexes;
132
- })();
133
- }
134
- drawRow(row) {
135
- var _a, _b, _c, _d, _e, _f, _g;
136
- let content = "";
137
- const context = this.context;
138
- const { columns } = context.metadata;
139
- const columnsCount = columns.length;
140
- if (getRowType(row) === SpecialRowTypeEnum.Default) {
141
- row = row;
142
- content += (_c = (_b = (_a = this.options).borderLeft) === null || _b === void 0 ? void 0 : _b.call(_a, context, context.currentRow)) !== null && _c !== void 0 ? _c : "";
143
- for (let cellIndex = 0; cellIndex < columnsCount; cellIndex++) {
144
- const cell = (_d = row.at(+cellIndex)) !== null && _d !== void 0 ? _d : emptyCell();
145
- const expectedWidth = columns.at(+cellIndex).largestLength;
146
- content += this.drawCell(cell, expectedWidth);
147
- if (+cellIndex !== columnsCount - 1) {
148
- content += !cell.options.removeNextSeparator
149
- ? this.options.separator
150
- : " ";
151
- }
152
- }
153
- content += (_g = (_f = (_e = this.options).borderRight) === null || _f === void 0 ? void 0 : _f.call(_e, context, context.currentRow)) !== null && _g !== void 0 ? _g : "";
154
- return content;
155
- }
156
- if (getRowType(row) === SpecialRowTypeEnum.Display) {
157
- row = row;
158
- content += this.drawLine(row.display);
159
- }
160
- return content;
161
- }
162
- drawCell(cell, expectedWidth) {
163
- const { gapLeft, gapRight, align } = cell.options;
164
- const { value } = cell;
165
- const minContentLength = calculateCellMinWidth(cell);
166
- const lack = expectedWidth - minContentLength;
167
- const contentWithPadding = addPaddingByCellAlign(value, lack, align);
168
- return `${" ".repeat(gapLeft)}${contentWithPadding}${" ".repeat(gapRight)}`;
169
- }
170
- drawLine(setSymbol) {
171
- let content = "";
172
- const context = this.context;
173
- const length = this.calculateTableWidth();
174
- for (const index of [...new Array(length)].map((_, index) => index)) {
175
- const symbol = setSymbol(context, +index);
176
- content += symbol;
177
- }
178
- return content;
179
- }
180
- drawBlockBorder(borderDirection) {
181
- const callback = borderDirection === BorderDirectionEnum.BorderTop
182
- ? this.options.borderTop
183
- : this.options.borderBottom;
184
- return this.drawLine(callback);
185
- }
186
- calculateTableWidth() {
187
- const { columns } = this.context.metadata;
188
- if (!columns) {
189
- throw new Error("No columns field; Tip: Use <this>.parseMetadata() previous");
190
- }
191
- const cells = columns.reduce((acc, current) => current.largestLength + acc, 0);
192
- const separators = columns.length - 1;
193
- const borders = +!!this.options.borderLeft + +!!this.options.borderRight;
194
- return cells + separators + borders;
195
- }
196
- }
197
- var CellAlignEnum;
198
- (function (CellAlignEnum) {
199
- CellAlignEnum[CellAlignEnum["Left"] = 0] = "Left";
200
- CellAlignEnum[CellAlignEnum["Right"] = 1] = "Right";
201
- CellAlignEnum[CellAlignEnum["Center"] = 2] = "Center";
202
- })(CellAlignEnum || (CellAlignEnum = {}));
203
- const DEFAULT_CELL_OPTIONS = {
204
- gapLeft: 2,
205
- gapRight: 2,
206
- align: CellAlignEnum.Left,
207
- };
208
- var BorderDirectionEnum;
209
- (function (BorderDirectionEnum) {
210
- BorderDirectionEnum[BorderDirectionEnum["BorderLeft"] = 0] = "BorderLeft";
211
- BorderDirectionEnum[BorderDirectionEnum["BorderRight"] = 1] = "BorderRight";
212
- BorderDirectionEnum[BorderDirectionEnum["BorderTop"] = 2] = "BorderTop";
213
- BorderDirectionEnum[BorderDirectionEnum["BorderBottom"] = 3] = "BorderBottom";
214
- })(BorderDirectionEnum || (BorderDirectionEnum = {}));
215
- const DEFAULT_TABLE_OPTIONS = {
216
- borderLeft: null,
217
- borderRight: null,
218
- borderTop: null,
219
- borderBottom: null,
220
- separator: "|",
221
- };
222
- var SpecialRowTypeEnum;
223
- (function (SpecialRowTypeEnum) {
224
- SpecialRowTypeEnum[SpecialRowTypeEnum["Default"] = 0] = "Default";
225
- SpecialRowTypeEnum[SpecialRowTypeEnum["Display"] = 1] = "Display";
226
- })(SpecialRowTypeEnum || (SpecialRowTypeEnum = {}));
227
- class TextTableBuilder {
228
- constructor() {
229
- this.rows = [];
230
- this.options = Object.assign({}, DEFAULT_TABLE_OPTIONS);
231
- }
232
- setBorderOptions(callback = () => "|", directions = [
233
- BorderDirectionEnum.BorderLeft,
234
- BorderDirectionEnum.BorderRight,
235
- ]) {
236
- for (const direction of directions) {
237
- switch (direction) {
238
- case BorderDirectionEnum.BorderLeft:
239
- this.options.borderLeft = callback;
240
- break;
241
- case BorderDirectionEnum.BorderRight:
242
- this.options.borderRight = callback;
243
- break;
244
- case BorderDirectionEnum.BorderTop:
245
- this.options.borderTop = callback;
246
- break;
247
- case BorderDirectionEnum.BorderBottom:
248
- this.options.borderBottom = callback;
249
- break;
250
- }
251
- }
252
- return this;
253
- }
254
- addRowWithElements(elements, optionsForEveryElement, useOnAddingOptions) {
255
- const row = [];
256
- for (const value of elements) {
257
- this.pushCellToArray(row, value, optionsForEveryElement, useOnAddingOptions);
258
- }
259
- this.pushRowToTable(row);
260
- return this;
261
- }
262
- addMultilineRowWithElements(elements, optionsForEveryElement, useOnAddingOptions) {
263
- const separatedElements = elements.map((value) => value.split("\n"));
264
- const largestHeight = Math.max(...separatedElements.map((sub) => sub.length));
265
- for (let index = 0; index < largestHeight; index++) {
266
- this.addRowWithElements(separatedElements.map((sub) => { var _a; return (_a = sub.at(index)) !== null && _a !== void 0 ? _a : ""; }), optionsForEveryElement, useOnAddingOptions);
267
- }
268
- return this;
269
- }
270
- addEmptyRow() {
271
- this.pushRowToTable([]);
272
- return this;
273
- }
274
- addRowSeparator(setSymbol = () => "-") {
275
- const row = {
276
- display: setSymbol,
277
- type: SpecialRowTypeEnum.Display,
278
- };
279
- this.pushRowToTable(row);
280
- return this;
281
- }
282
- addCellAtRow(rowIndex, cellValue, cellOptions, useOnAddingOptions) {
283
- const row = this.rows.at(rowIndex);
284
- if (!row) {
285
- throw new RangeError();
286
- }
287
- if (getRowType(row) !== SpecialRowTypeEnum.Default) {
288
- throw new Error("Is not default row: without cells");
289
- }
290
- this.pushCellToArray(row, cellValue, cellOptions, useOnAddingOptions);
291
- return this;
292
- }
293
- pushCellToArray(array, cellValue, cellOptions = {}, pushOptions) {
294
- const options = Object.assign({}, DEFAULT_CELL_OPTIONS, cellOptions);
295
- const cell = { value: cellValue, options };
296
- const { minWidth, maxWidth } = pushOptions !== null && pushOptions !== void 0 ? pushOptions : {};
297
- minWidth && changeContentSetCellMinWidth(cell, minWidth);
298
- maxWidth && changeContentSetCellMaxWidth(cell, maxWidth);
299
- array.push(cell);
300
- return this;
301
- }
302
- pushRowToTable(row) {
303
- this.rows.push(row);
304
- return this;
305
- }
306
- generateTextContent() {
307
- return new TextTableGenerator(this.rows, this.options).generateTextContent();
308
- }
309
- addRowWithUnwrappedCells(cells, useOnAddingOptions) {
310
- const row = [];
311
- for (const cell of cells) {
312
- this.pushCellToArray(row, cell.value, cell.options, useOnAddingOptions);
313
- }
314
- this.pushRowToTable(row);
315
- return this;
316
- }
317
- }
318
- export { TextTableBuilder };
319
- export { SpecialRowTypeEnum, CellAlignEnum, BorderDirectionEnum };
@@ -1,6 +0,0 @@
1
- export * from './TextTableBuilder.js';
2
- interface IEndingOptions {
3
- unite?: (quantity: number, word: string) => string;
4
- }
5
- declare function ending(quantity: number | undefined, base: string, multiple: string, alone: string, double: string, options?: IEndingOptions): string | number;
6
- export { ending };
@@ -1,12 +0,0 @@
1
- export * from './TextTableBuilder.js';
2
- function ending(quantity = 0, base, multiple, alone, double, options = {}) {
3
- if (isNaN(quantity))
4
- return NaN;
5
- const target = quantity % 100 < 20 ? quantity % 20 : quantity % 10;
6
- const end = target >= 5 || target === 0 ? multiple : target > 1 ? double : alone;
7
- const word = base + end;
8
- options.unite || (options.unite = (quantity, word) => `${quantity} ${word}`);
9
- const input = options.unite(quantity, word);
10
- return input;
11
- }
12
- export { ending };