diff --git a/CHANGELOG.md b/CHANGELOG.md index bada6b4..ef3adc8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,11 @@ +## [8.5.2-beta.1](https://github.com/vodyani/utils/compare/v8.5.1...v8.5.2-beta.1) (2022-09-07) + + +### Bug Fixes + +* delete unnecessary types ([768cd62](https://github.com/vodyani/utils/commit/768cd62ff21aef09fb69fecab35b0ce9ef0d4040)) +* simplify naming and method calls ([57fc440](https://github.com/vodyani/utils/commit/57fc440e997ad1d8f4a2e67c128e8c89a2faed5d)) + ## [8.5.1](https://github.com/vodyani/utils/compare/v8.5.0...v8.5.1) (2022-08-31) diff --git a/package-lock.json b/package-lock.json index b803a36..98af9e1 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@vodyani/utils", - "version": "8.5.1", + "version": "8.5.2-beta.1", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "@vodyani/utils", - "version": "8.5.1", + "version": "8.5.2-beta.1", "license": "MIT", "dependencies": { "deepmerge-ts": "4.2.1", diff --git a/package.json b/package.json index 3c6c272..2826455 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@vodyani/utils", "license": "MIT", - "version": "8.5.1", + "version": "8.5.2-beta.1", "author": "ChoGathK", "description": "🏃🏻‍♀️ utils provides common utility functions used in server-side development.", "homepage": "https://github.com/vodyani/utils#readme", diff --git a/src/common.ts b/src/common.ts new file mode 100644 index 0000000..41f002f --- /dev/null +++ b/src/common.ts @@ -0,0 +1,31 @@ +export interface ConvertOptions { + /** + * When the received value does not correspond to expectations, this value is returned. + * + * @default null + */ + default?: any; + /** + * The conversion is carried out if the outcome of the conditional validation function execution is true. + * + * @empale (num: number) => num > 0 + */ + condition?: (...args: any[]) => boolean; + /** + * The process that carries out the transition. + * + * @empale (data: any) => Number(data) + */ + transformer?: Function; +} + +export class PriorityElement { + /** + * Priority Indicates the weight of the queue. + */ + public weight: number; + /** + * The actual content. + */ + public value: T; +} diff --git a/src/common/index.ts b/src/common/index.ts deleted file mode 100644 index a447691..0000000 --- a/src/common/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './interface'; -export * from './type'; diff --git a/src/common/interface.ts b/src/common/interface.ts deleted file mode 100644 index 828676e..0000000 --- a/src/common/interface.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { Method } from './type'; - -export interface RetryOptions { - /** The retry count. */ - count: number; - /** The waiting time (The time unit is milliseconds). */ - delay: number; - /** The callback argument.*/ - args?: any[]; -} - -export interface CycleOptions { - /** The cycle time, default 1000 (The time unit is milliseconds). */ - interval: number; - /** The callback argument. */ - args?: any[]; -} - -export interface CycleClearHandler { - /** The closes timed calls. */ - close: () => void -} - -export interface ConvertOptions { - /** - * When the received value does not correspond to expectations, this value is returned. - * - * @default null - */ - default?: any; - /** - * The conversion is carried out if the outcome of the conditional validation function execution is true. - * - * @empale (num: number) => num > 0 - */ - condition?: Method; - /** - * The process that carries out the transition. - * - * @empale (data: any) => Number(data) - */ - transformer?: Method; -} - -export class PriorityQueueElement { - public weight: number; - - public value: T; -} diff --git a/src/common/type.ts b/src/common/type.ts deleted file mode 100644 index c6d9d38..0000000 --- a/src/common/type.ts +++ /dev/null @@ -1,7 +0,0 @@ -export type Method = (...args: any[]) => T; - -export type PromiseMethod = (...args: any[]) => Promise; - -export type Dictionary = { [P in keyof T]: T[P]; }; - -export type SortRule = 'DESC' | 'ASC'; diff --git a/src/method/circular.ts b/src/method/circular.ts new file mode 100644 index 0000000..29c71af --- /dev/null +++ b/src/method/circular.ts @@ -0,0 +1,30 @@ +/** + * Create a recurring scheduled task. + * + * @param callback A callback function that needs to be called periodically. + * @param interval number The cycle time, default 1000 (The time unit is milliseconds). + * @param args any[] The callback argument. + * + * @publicApi + */ +export function circular(callback: Function, interval: number, ...args: any[]) { + let timer: NodeJS.Timeout = null; + + const close = () => { + if (timer) clearTimeout(timer); + }; + + const regularly = () => { + close(); + timer = setTimeout(regularlyHandler, interval); + }; + + const regularlyHandler = () => { + callback(...args); + regularly(); + }; + + regularly(); + + return { close }; +} diff --git a/src/method/convert.ts b/src/method/convert.ts new file mode 100644 index 0000000..09bd466 --- /dev/null +++ b/src/method/convert.ts @@ -0,0 +1,110 @@ +import { isEmpty, isMap, isNil } from 'lodash'; + +import { ConvertOptions } from '../common'; + +import { isValid, isValidArray, isValidDict } from './validate'; + +/** + * Formatting properties of the object in the data. + * + * @param data The source data (`Array`|`Object`|`Map`). + * @param transformer A callback function used to convert properties. + * @returns any + * + * @publicApi + * + * @tips Because this method uses recursion, it can cause stack overflows when the hierarchy is too deep ! + */ +export function toDeepConvertProperty(data: any, transformer: Function): any { + if (isNil(data)) return data; + + let result = null; + + const pipe = [ + { + isAllowUse: isMap(data), + use: () => { + const result = new Map(); + (data as Map).forEach((v, k) => result.set(transformer(k), v)); + return result; + }, + }, + { + isAllowUse: isValidArray(data), + use: () => { + return data.map((item: any) => toDeepConvertProperty(item, transformer)); + }, + }, + { + isAllowUse: isValidDict(data), + use: () => { + const result = Object(); + Object.keys(data).forEach((key: any) => { + result[transformer(key)] = toDeepConvertProperty(data[key], transformer); + }); + return result; + }, + }, + ]; + + for (const { isAllowUse, use } of pipe) { + if (isAllowUse) { + result = use(); + break; + } + + result = data; + } + + return result; +} +/** + * The process that carries out the transition. + * + * @tips There are two outcomes that return the `default`: `default` is entered and either the condition fails or the value is null. + * + * @param data Data that needs to be transformed. + * @param options Options in transformation processing. + * + * @publicApi + */ +export function toConvert(data: any, options?: ConvertOptions): T { + const { condition, transformer, default: value } = options || Object(); + + if (condition) { + if (transformer && condition(data)) return transformer(data); + if (isValid(value)) return value; + } + + return isNil(data) && isValid(value) ? value : data; +} +/** + * Convert data to string. + * + * @param data Data that needs to be transformed. + * @param defaultValue This value is returned when the incoming value does not match expectations. + * + * @publicApi + */ +export function toString(data: any, defaultValue = ''): string { + return toConvert(data, { + transformer: String, + default: defaultValue, + condition: (data) => isValid(data) && !isEmpty(String(data)), + }); +} +/** + * Convert data to number. + * + * @param data Data that needs to be transformed. + * @param defaultValue This value is returned when the incoming value does not match expectations. + * + * @publicApi + */ +export function toNumber(data: any, defaultValue = 0): number { + return toConvert(data, { + transformer: Number, + default: defaultValue, + condition: (data) => isValid(data) && Number.isSafeInteger(Number(data)), + }); +} diff --git a/src/method/index.ts b/src/method/index.ts index 7435efa..a7ca621 100644 --- a/src/method/index.ts +++ b/src/method/index.ts @@ -1,3 +1,7 @@ -export * from './transform'; -export * from './promise'; +export * from './circular'; +export * from './convert'; +export * from './object'; +export * from './retry'; +export * from './sleep'; +export * from './stream'; export * from './validate'; diff --git a/src/method/object.ts b/src/method/object.ts new file mode 100644 index 0000000..7edf604 --- /dev/null +++ b/src/method/object.ts @@ -0,0 +1,110 @@ +import { deepmerge } from 'deepmerge-ts'; +import { isNil, isObject } from 'lodash'; + +import { isValid, isValidDict, isValidString } from './validate'; + +/** + * Walks deeply through the object and returns the property value corresponding to the specified parameter. + * + * @param obj The object to judge. + * @param token The properties of the object and splice them with `rule`. + * @param rule The rules for splicing, by default, are `.`. + * @returns T + * + * @example + * ```ts + * toDeepMatch({ job: { name: 'job' }}, 'job.name') // 'job' + * ``` + * + * @publicApi + */ +export function toDeepMatch(obj: any, token: string, rule = '.'): T { + if (!isValidString(rule) || !isValidDict(obj)) return null; + + const stack = []; + const factors = token.split(rule); + + let node; + let nodeResult = null; + let nodeDeepLevel = 0; + + stack.push(obj); + + while (stack.length > 0) { + node = stack.pop(); + + if (nodeDeepLevel === factors.length) { + nodeResult = node; + break; + } + + if (isValidDict(node)) { + for (const key of Object.keys(node)) { + const indexResult = factors.indexOf(key); + const factorResult = factors[nodeDeepLevel]; + + if (key === factorResult && indexResult === nodeDeepLevel) { + stack.push(node[key]); + nodeDeepLevel += 1; + break; + } + } + } + } + + return nodeResult; +} +/** + * Restores to the corresponding object based on the depth of the specified property and property value. + * + * @param value The object properties value. + * @param token The properties of the object and splice them with `rule`. + * @param rule The rules for splicing, by default, are `.`. + * @returns T + * + * @example + * ```ts + * toDeepRestore('job', 'job.name') // { job: { name: 'job' }} + * ``` + * + * @publicApi + */ +export function toDeepRestore(value: any, token: string, rule = '.'): T { + if (isNil(token) || !isValidString(token)) return null; + + const object = Object(); + const factors = token.split(rule); + + let node = object; + + while (factors.length > 0) { + const key = factors.shift(); + + node[key] = Object(); + + if (factors.length === 0) { + node[key] = value; + } else { + node = node[key]; + } + } + + return object; +} +/** + * Deep comparison and fusion are performed on the two incoming data. + * + * @tips `base` will be deeply copied before merging, so it will not be changed. + * + * @param base The underlying data being compared. + * @param source New data merged into the underlying data. + * @returns `T` | `any` + * + * @publicApi + */ +export function toDeepMerge(base: any, source: any): T { + if (isValid(base) && isNil(source)) return base; + if (!(isObject(base) && isObject(source))) return source; + + return deepmerge(base, source) as any; +} diff --git a/src/method/promise.ts b/src/method/promise.ts deleted file mode 100644 index d013501..0000000 --- a/src/method/promise.ts +++ /dev/null @@ -1,85 +0,0 @@ -import { CycleClearHandler, CycleOptions, RetryOptions } from '../common'; - -import { isValid } from './validate'; - -/** - * Wait during an asynchronous function call. - * - * @param delay The waiting time (The time unit is milliseconds). - * @returns Promise - * - * @publicApi - */ -export function toDelay(delay: number) { - return new Promise(resolve => setTimeout(() => resolve(), delay)); -} -/** - * Create a recurring scheduled task. - * - * @param callback A callback function that needs to be called periodically. - * @param options Configuration options when triggered. - * @returns CycleClearHandler - Returns a method that closes timed calls. - * - * @publicApi - */ -export function toCycle(callback: Function, options: CycleOptions): CycleClearHandler { - let timeOutHandler: NodeJS.Timeout = null; - const args = options.args || []; - - const regularly = () => { - close(); - timeOutHandler = setTimeout(regularlyHandler, options.interval); - }; - - const clearHandler = () => { - clearTimeout(timeOutHandler); - timeOutHandler = null; - }; - - const regularlyHandler = () => { - callback(...args); - regularly(); - }; - - const close = () => { - if (isValid(timeOutHandler)) clearHandler(); - }; - - regularly(); - - return { close }; -} -/** - * Create a caller that can retry the callback function. - * - * @param callback The callback function to call. - * @param options Configuration options when triggered. - * @returns T - * - * @publicApi - */ -export async function toRetry(callback: Function, options: RetryOptions): Promise { - let result = null; - let currentCount = options.count; - const currentDelay = options.delay; - const currentArgs = options.args || []; - - try { - result = await callback(...currentArgs); - } catch (error) { - currentCount--; - - // No chance to try again - if (currentCount === 0) throw new Error(error); - - // If need delay retry ... - if (currentDelay) await toDelay(currentDelay); - - result = await toRetry( - callback, - { count: currentCount, delay: currentDelay, args: currentArgs }, - ); - } - - return result; -} diff --git a/src/method/retry.ts b/src/method/retry.ts new file mode 100644 index 0000000..0c38e35 --- /dev/null +++ b/src/method/retry.ts @@ -0,0 +1,35 @@ +import { sleep } from './sleep'; + +/** + * Create a caller that can retry the callback function. + * + * @param callback The callback function to call. + * @param count The retry count. + * @param delay The waiting time (The time unit is milliseconds). + * @param args any[] The callback argument. + * + * @publicApi + */ +export async function retry(callback: Function, count: number, delay: number, ...args: any[]): Promise { + let result = null; + let currentCount = count; + + try { + result = await callback(...args); + } catch (error) { + currentCount--; + + if (currentCount === 0) throw new Error(error); + + if (delay) await sleep(delay); + + result = await retry( + callback, + currentCount, + delay, + ...args, + ); + } + + return result; +} diff --git a/src/method/sleep.ts b/src/method/sleep.ts new file mode 100644 index 0000000..448abcc --- /dev/null +++ b/src/method/sleep.ts @@ -0,0 +1,10 @@ +/** + * Wait during an asynchronous function call. + * + * @param delay The waiting time (The time unit is milliseconds). + * + * @publicApi + */ +export function sleep(delay: number) { + return new Promise(resolve => setTimeout(() => resolve(), delay)); +} diff --git a/src/method/stream.ts b/src/method/stream.ts new file mode 100644 index 0000000..dfbdc97 --- /dev/null +++ b/src/method/stream.ts @@ -0,0 +1,33 @@ +import { Stream, Duplex } from 'stream'; + +/** + * Convert `Stream` data to `Buffer`. + * + * @param stream Data that needs to be transformed. + * @returns Promise + * + * @publicApi + */ +export async function toBuffer(stream: Stream): Promise { + return new Promise((resolve, reject) => { + const buffers: Uint8Array[] = []; + stream.on('error', reject); + stream.on('data', (data) => buffers.push(data)); + stream.on('end', () => resolve(Buffer.concat(buffers))); + }); +} +/** + * Convert `Buffer` data to `Stream`. + * + * @param buffer Data that needs to be transformed. + * @param encoding The encoding type. + * @returns Promise + * + * @publicApi + */ +export async function toStream(buffer: Buffer, encoding?: BufferEncoding): Promise { + const stream = new Duplex(); + stream.push(buffer, encoding); + stream.push(null, encoding); + return stream; +} diff --git a/src/method/transform.ts b/src/method/transform.ts deleted file mode 100644 index 1ad3c96..0000000 --- a/src/method/transform.ts +++ /dev/null @@ -1,252 +0,0 @@ -import { Stream, Duplex } from 'stream'; - -import { deepmerge } from 'deepmerge-ts'; -import { isEmpty, isMap, isNil, isObject } from 'lodash'; - -import { ConvertOptions, Method } from '../common'; - -import { isValid, isValidArray, isValidDict, isValidString } from './validate'; - -/** - * The process that carries out the transition. - * - * @tips There are two outcomes that return the `default`: `default` is entered and either the condition fails or the value is null. - * - * @param data Data that needs to be transformed. - * @param options Options in transformation processing. - * @returns `T` | `any` - * - * @publicApi - */ -export function toConvert(data: any, options?: ConvertOptions): T { - const { condition, transformer, default: value } = options || Object(); - - if (condition) { - if (transformer && condition(data)) return transformer(data); - if (isValid(value)) return value; - } - - return isNil(data) && isValid(value) ? value : data; -} -/** - * Convert data to string. - * - * @param data Data that needs to be transformed. - * @param defaultValue This value is returned when the incoming value does not match expectations. - * @returns string - * - * @publicApi - */ -export function toString(data: any, defaultValue = ''): string { - return toConvert(data, { - transformer: String, - default: defaultValue, - condition: (data) => isValid(data) && !isEmpty(String(data)), - }); -} -/** - * Convert data to number. - * - * @param data Data that needs to be transformed. - * @param defaultValue This value is returned when the incoming value does not match expectations. - * @returns number - * - * @publicApi - */ -export function toNumber(data: any, defaultValue = 0): number { - return toConvert(data, { - transformer: Number, - default: defaultValue, - condition: (data) => isValid(data) && Number.isSafeInteger(Number(data)), - }); -} -/** - * Convert `Stream` data to `Buffer`. - * - * @param stream Data that needs to be transformed. - * @returns Promise - * - * @publicApi - */ -export async function toBuffer(stream: Stream): Promise { - return new Promise((resolve, reject) => { - const buffers: Uint8Array[] = []; - stream.on('error', reject); - stream.on('data', (data) => buffers.push(data)); - stream.on('end', () => resolve(Buffer.concat(buffers))); - }); -} -/** - * Convert `Buffer` data to `Stream`. - * - * @param buffer Data that needs to be transformed. - * @param encoding The encoding type. - * @returns Promise - * - * @publicApi - */ -export async function toStream(buffer: Buffer, encoding?: BufferEncoding): Promise { - const stream = new Duplex(); - stream.push(buffer, encoding); - stream.push(null, encoding); - return stream; -} -/** - * Walks deeply through the object and returns the property value corresponding to the specified parameter. - * - * @param obj The object to judge. - * @param token The properties of the object and splice them with `rule`. - * @param rule The rules for splicing, by default, are `.`. - * @returns T - * - * @example - * ```ts - * toDeepMatch({ job: { name: 'job' }}, 'job.name') // 'job' - * ``` - * - * @publicApi - */ -export function toDeepMatch(obj: any, token: string, rule = '.'): T { - if (!isValidString(rule) || !isValidDict(obj)) return null; - - const stack = []; - const factors = token.split(rule); - - let node; - let nodeResult = null; - let nodeDeepLevel = 0; - - stack.push(obj); - - while (stack.length > 0) { - node = stack.pop(); - - if (nodeDeepLevel === factors.length) { - nodeResult = node; - break; - } - - if (isValidDict(node)) { - for (const key of Object.keys(node)) { - const indexResult = factors.indexOf(key); - const factorResult = factors[nodeDeepLevel]; - - if (key === factorResult && indexResult === nodeDeepLevel) { - stack.push(node[key]); - nodeDeepLevel += 1; - break; - } - } - } - } - - return nodeResult; -} -/** - * Restores to the corresponding object based on the depth of the specified property and property value. - * - * @param value The object properties value. - * @param token The properties of the object and splice them with `rule`. - * @param rule The rules for splicing, by default, are `.`. - * @returns T - * - * @example - * ```ts - * toDeepRestore('job', 'job.name') // { job: { name: 'job' }} - * ``` - * - * @publicApi - */ -export function toDeepRestore(value: any, token: string, rule = '.'): T { - if (isNil(token) || !isValidString(token)) return null; - - const object = Object(); - const factors = token.split(rule); - - let node = object; - - while (factors.length > 0) { - const key = factors.shift(); - - node[key] = Object(); - - if (factors.length === 0) { - node[key] = value; - } else { - node = node[key]; - } - } - - return object; -} -/** - * Deep comparison and fusion are performed on the two incoming data. - * - * @tips `base` will be deeply copied before merging, so it will not be changed. - * - * @param base The underlying data being compared. - * @param source New data merged into the underlying data. - * @returns `T` | `any` - * - * @publicApi - */ -export function toDeepMerge(base: any, source: any): T { - if (isValid(base) && isNil(source)) return base; - if (!(isObject(base) && isObject(source))) return source; - - return deepmerge(base, source) as any; -} -/** - * Formatting properties of the object in the data. - * - * @param data The source data (`Array`|`Object`|`Map`). - * @param transformer A callback function used to convert properties. - * @returns any - * - * @publicApi - * - * @tips Because this method uses recursion, it can cause stack overflows when the hierarchy is too deep ! - */ -export function toDeepConvertProperty(data: any, transformer: Method): any { - if (isNil(data)) return data; - - let result = null; - - const pipe = [ - { - isAllowUse: isMap(data), - use: () => { - const result = new Map(); - (data as Map).forEach((v, k) => result.set(transformer(k), v)); - return result; - }, - }, - { - isAllowUse: isValidArray(data), - use: () => { - return data.map((item: any) => toDeepConvertProperty(item, transformer)); - }, - }, - { - isAllowUse: isValidDict(data), - use: () => { - const result = Object(); - Object.keys(data).forEach((key: any) => { - result[transformer(key)] = toDeepConvertProperty(data[key], transformer); - }); - return result; - }, - }, - ]; - - for (const { isAllowUse, use } of pipe) { - if (isAllowUse) { - result = use(); - break; - } - - result = data; - } - - return result; -} diff --git a/src/method/validate.ts b/src/method/validate.ts index 913d681..ab0e2d8 100644 --- a/src/method/validate.ts +++ b/src/method/validate.ts @@ -2,11 +2,21 @@ import { Stream } from 'stream'; import { isArray, isBuffer, isMap, isNil, isNumber, isObject, isSet, isString, isSymbol } from 'lodash'; +/** + * Determines whether the object contains the current attribute. + * + * @param obj The object to judge. + * @param key The property of object. + * + * @publicApi + */ +export function isKeyof(obj: object, key: any): key is keyof typeof obj { + return key in obj && Object.prototype.hasOwnProperty.call(obj, key); +} /** * Checks if the data is non-empty. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -17,7 +27,6 @@ export function isValid(data: any): boolean { * Checks if the data is non-empty string. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -28,7 +37,6 @@ export function isValidString(data: string): boolean { * Checks if the data is non-empty number (Also it will not be NAN or plus or minus infinity). * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -39,7 +47,6 @@ export function isValidNumber(data: number): boolean { * Checks if the data is non-empty array. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -50,7 +57,6 @@ export function isValidArray(data: any[]): boolean { * Checks if the data is non-empty object. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -61,7 +67,6 @@ export function isValidObject(data: any): boolean { * Checks if the data is stream. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -72,7 +77,6 @@ export function isValidStream(data: Stream) { * Checks if the data is buffer. * * @param data The data to be check. - * @returns boolean * * @publicApi */ @@ -85,7 +89,6 @@ export function isValidBuffer(data: Buffer) { * Dictionary is not in (`Map`/`Set`/`Symbol`/`Array`/`String`/`Number`/`Boolean`). * * @param dict The object to judge. - * @returns boolean * * @publicApi */ @@ -99,15 +102,3 @@ export function isValidDict(dict: any) { && !(dict instanceof Number) && !(dict instanceof Boolean); } -/** - * Determines whether the object contains the current attribute. - * - * @param obj The object to judge. - * @param key The property of object. - * @returns (is keyof typeof obj) - * - * @publicApi - */ -export function isKeyof(obj: object, key: string | number): key is keyof typeof obj { - return key in obj && Object.prototype.hasOwnProperty.call(obj, key); -} diff --git a/src/struct/priority-queue.ts b/src/struct/priority-queue.ts index 03761a2..ac7eedb 100644 --- a/src/struct/priority-queue.ts +++ b/src/struct/priority-queue.ts @@ -1,12 +1,12 @@ +import { PriorityElement } from '../common'; import { isValid, isValidNumber } from '../method'; -import { PriorityQueueElement, SortRule } from '../common'; export class PriorityQueue { private readonly sort: Function; - private readonly data: PriorityQueueElement[] = []; + private readonly data: PriorityElement[] = []; - constructor(rule?: SortRule) { + constructor(rule?: 'DESC' | 'ASC') { this.sort = (_before: number, _after: number) => { return rule === 'ASC' ? _before - _after : _after - _before; }; @@ -24,11 +24,11 @@ export class PriorityQueue { return this.data.length; } - public pop(): PriorityQueueElement { + public pop(): PriorityElement { return this.data.pop(); } - public peek(): PriorityQueueElement { + public peek(): PriorityElement { return this.data[this.data.length - 1]; } diff --git a/test/method/convert.spec.ts b/test/method/convert.spec.ts index 7c38007..9177813 100644 --- a/test/method/convert.spec.ts +++ b/test/method/convert.spec.ts @@ -1,8 +1,3 @@ -/* eslint-disable no-buffer-constructor */ -/* eslint-disable @typescript-eslint/no-array-constructor */ -/* eslint-disable no-array-constructor */ -/* eslint-disable no-new-wrappers */ -/* eslint-disable no-undefined */ import { range, camelCase } from 'lodash'; import { describe, it, expect } from '@jest/globals'; diff --git a/test/method/promise.spec.ts b/test/method/promise.spec.ts index c8a8a05..36053d5 100644 --- a/test/method/promise.spec.ts +++ b/test/method/promise.spec.ts @@ -1,19 +1,19 @@ import { describe, it, expect } from '@jest/globals'; import { - toDelay, - toRetry, - toCycle, + sleep, + retry, + circular, } from '../../src'; describe('promise', () => { - it('toDelay', async () => { + it('sleep', async () => { const start = Date.now(); - await toDelay(300); + await sleep(300); expect(Date.now() - start).toBeGreaterThanOrEqual(299); }); - it('toRetry', async () => { + it('retry', async () => { let count = 0; const fn = async () => { @@ -25,12 +25,12 @@ describe('promise', () => { return count; }; - const result = await toRetry(fn, { delay: 100, count: 3 }); + const result = await retry(fn, 3, 100); expect(result).toBe(1); }); - it('toRetry.error', async () => { + it('retry.error', async () => { let result = 0; const fn = async () => { @@ -38,7 +38,7 @@ describe('promise', () => { }; try { - result = await toRetry(fn, { delay: 100, count: 3 }); + result = await retry(fn, 3, 100); } catch (error) { expect(error.message).toBe('Error: async error'); } @@ -46,34 +46,34 @@ describe('promise', () => { expect(result).toBe(0); }); - it('toCycle', async () => { + it('circular', async () => { let count = 0; const fn = () => { count++; }; - const { close } = toCycle(fn, { interval: 100 }); + const { close } = circular(fn, 100); - await toDelay(250); + await sleep(250); close(); expect(count).toBeGreaterThanOrEqual(1); }); - it('toCycle.clear', async () => { + it('circular.clear', async () => { let count = 0; const fn = () => { count++; }; - const { close } = toCycle(fn, { interval: 100 }); + const { close } = circular(fn, 100); close(); - await toDelay(300); + await sleep(300); expect(count).toBe(0); }); diff --git a/test/method/validate.spec.ts b/test/method/validate.spec.ts index 4e3bc8f..90282d6 100644 --- a/test/method/validate.spec.ts +++ b/test/method/validate.spec.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-new-wrappers */ import { Stream } from 'stream'; import { describe, it, expect } from '@jest/globals'; @@ -10,9 +9,9 @@ describe('validate', () => { expect(isValidDict({ name: 'dict' })).toBe(true); expect(isValidDict({})).toBe(false); expect(isValidDict(Object())).toBe(false); - expect(isValidDict(new String())).toBe(false); - expect(isValidDict(new Number())).toBe(false); - expect(isValidDict(new Boolean())).toBe(false); + expect(isValidDict(String())).toBe(false); + expect(isValidDict(Number())).toBe(false); + expect(isValidDict(Boolean())).toBe(false); expect(isValidDict(new Map())).toBe(false); expect(isValidDict(new Set())).toBe(false); expect(isValidDict([])).toBe(false); @@ -34,7 +33,6 @@ describe('validate', () => { }); it('isValid', async () => { - // eslint-disable-next-line no-undefined expect(isValid(undefined)).toBe(false); expect(isValid(null)).toBe(false); expect(isValid([])).toBe(true); @@ -45,7 +43,6 @@ describe('validate', () => { }); it('isValidArray', async () => { - // eslint-disable-next-line no-undefined expect(isValidArray(undefined as any)).toBe(false); expect(isValidArray(null as any)).toBe(false); expect(isValidArray([])).toBe(false); @@ -56,7 +53,6 @@ describe('validate', () => { }); it('isValidNumber', async () => { - // eslint-disable-next-line no-undefined expect(isValidNumber(undefined as any)).toBe(false); expect(isValidNumber(null as any)).toBe(false); expect(isValidNumber(0)).toBe(true); @@ -67,7 +63,6 @@ describe('validate', () => { }); it('isValidObject', async () => { - // eslint-disable-next-line no-undefined expect(isValidObject(undefined)).toBe(false); expect(isValidObject(null)).toBe(false); expect(isValidObject({})).toBe(false); @@ -75,7 +70,6 @@ describe('validate', () => { }); it('isValidString', async () => { - // eslint-disable-next-line no-undefined expect(isValidString(undefined as any)).toBe(false); expect(isValidString(null as any)).toBe(false); expect(isValidString('')).toBe(false); diff --git a/test/tsconfig.json b/test/tsconfig.json new file mode 100644 index 0000000..5abfbcc --- /dev/null +++ b/test/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../tsconfig.json", + "include": ["**/*.spec.ts"], + "exclude": ["node_modules", "dist"], +} \ No newline at end of file