Skip to content

Commit

Permalink
Almost done with adding docs to the utils, rework certain things and …
Browse files Browse the repository at this point in the history
…move the chain promise utils to functions
  • Loading branch information
alchemicas committed Dec 24, 2023
1 parent 3f22827 commit 3049f17
Show file tree
Hide file tree
Showing 32 changed files with 701 additions and 386 deletions.
13 changes: 6 additions & 7 deletions src/classes/cookie.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { KeyOf, Primitive } from '../definitions/types.js'
import { mtc } from '../functions/mtc.js'
import { ClassLogger } from '../loggers/class-logger.js'
import { deserializeCookie, serializeCookie } from '../utils/cookie-utils.js'
import { setObjectProperty } from '../utils/object-utils.js'
import { isObject, setObjectProperty } from '../utils/object-utils.js'

/**
* The Cookie class is an abstraction to implement any cookie API in an uniform way.
Expand Down Expand Up @@ -219,13 +219,12 @@ export class Cookie {

protected serialize(key: string, value: string, options?: CookieSerializeOptions): string | Error
protected serialize<T extends CookieItem>(key: string, ik: keyof T, value: Primitive, options?: CookieSerializeOptions): string | Error
protected serialize<T extends CookieItem>(...args: any[]): string | Error {
let key: string, ik: keyof T | undefined, value: Primitive, options: CookieSerializeOptions | undefined
protected serialize<T extends CookieItem>(key: string, ...args: any[]): string | Error {
let ik: keyof T | undefined, value: Primitive, options: CookieSerializeOptions | undefined

key = args[0]
ik = typeof args[2] !== 'object' ? args[1] : undefined
value = typeof args[2] !== 'object' ? args[2] : args[1]
options = typeof args[2] !== 'object' ? args[3] : args[2]
ik = isObject(args[1]) ? undefined : args[0]
value = isObject(args[1]) ? args[0] : args[1]
options = isObject(args[1]) ? args[1] : args[2]

return serializeCookie(typeof ik === 'undefined' ? key : this.toDocumentCookieName(key, ik), String(value), options)
}
Expand Down
8 changes: 4 additions & 4 deletions src/classes/history.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DEFAULT_HISTORY_SIZE } from '../definitions/constants.js'
import { HistoryDataTarget } from '../definitions/interfaces.js'
import { ClassLogger } from '../loggers/class-logger.js'
import { cloneDeepObject } from '../utils/object-utils.js'
import { cloneObject } from '../utils/object-utils.js'

export class History<T extends HistoryDataTarget = HistoryDataTarget, K extends keyof T = keyof T> {
index: number
Expand All @@ -15,7 +15,7 @@ export class History<T extends HistoryDataTarget = HistoryDataTarget, K extends
this.key = key
this.size = size
this.target = target
this.versions = [cloneDeepObject(this.target[this.key])]
this.versions = [cloneObject(this.target[this.key], 'deep')]
}

redo(): void {
Expand All @@ -40,13 +40,13 @@ export class History<T extends HistoryDataTarget = HistoryDataTarget, K extends
ClassLogger.debug('History', 'push', `The first version has been removed.`)
}

this.versions = [...this.versions, cloneDeepObject(this.target[this.key])]
this.versions = [...this.versions, cloneObject(this.target[this.key], 'deep')]
this.index = this.versions.length - 1
}

protected setIndex(offset: number): void {
this.index = this.index + offset
this.target[this.key] = cloneDeepObject(this.versions[this.index])
this.target[this.key] = cloneObject(this.versions[this.index], 'deep')
}

get isPushable(): boolean {
Expand Down
4 changes: 2 additions & 2 deletions src/classes/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ export class Logger {
* Gets the level from the environment variables.
*/
protected static getLevelFromEnvironment(name: string): LoggerLevel | undefined {
let value: string
let value: string | undefined

value = getProcessEnvKey(`LOGGER_${name.toUpperCase()}_LEVEL`)
if (!LOGGER_LEVELS.includes(value as LoggerLevel)) return
Expand All @@ -209,7 +209,7 @@ export class Logger {
* Gets the status from the environment variables.
*/
protected static getStatusFromEnvironment(name: string): LoggerStatus | undefined {
let value: string
let value: string | undefined

value = getProcessEnvKey(`LOGGER_${name.toUpperCase()}_STATUS`)
if (!LOGGER_STATUSES.includes(value as LoggerStatus)) return
Expand Down
15 changes: 11 additions & 4 deletions src/definitions/constants.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import { random } from 'nanoid'
import { ConfigurationFunctions } from './interfaces.js'
import {
ArrayIncludes,
ArrayRemoves,
DebounceMapKey,
DebounceMapValue,
DeleteObjectPropertiesPredicate,
GenerateRandomStringRandom,
HasArrayItemPredicate,
IntervalMapKey,
IntervalMapValue,
LoggerLevel,
LoggerStatus,
RemoveArrayItemsPredicate,
StatusTransformer,
ThrottleMapKey,
TimeoutMapKey,
Expand All @@ -34,8 +35,8 @@ export const DEFAULT_APPEARENCE_STORAGE_KEY: string = 'appearence'
* Array Utils
*/
/** */
export const DEFAULT_ARRAY_INCLUDES: ArrayIncludes<any> = (array: any[], item: any) => array.includes(item)
export const DEFAULT_ARRAY_REMOVES: ArrayRemoves<any> = (array: any[], item: any) => array.includes(item)
export const DEFAULT_HAS_ARRAY_ITEM_PREDICATE: HasArrayItemPredicate<any> = (array: any[], item: any) => array.includes(item)
export const DEFAULT_REMOVE_ARRAY_ITEMS_PREDICATE: RemoveArrayItemsPredicate<any> = (array: any[], item: any, items?: any[]) => items?.includes(item) ?? false

/**
* Configuration
Expand Down Expand Up @@ -108,6 +109,12 @@ export const MEMORY_STORAGE_MAP: Map<PropertyKey, any> = new Map()
* Object Utils
*/
/** */
export const DEFAULT_DELETE_OBJECT_PROPERTIES_PREDICATE: DeleteObjectPropertiesPredicate<any, any> = (_, key: any, __, keys?: any[]) =>
keys?.includes(key) ?? false
export const DEFAULT_OMIT_OBJECT_PROPERTIES_PREDICATE: DeleteObjectPropertiesPredicate<any, any> = (_, key: any, __, keys?: any[]) =>
keys?.includes(key) ?? false
export const DEFAULT_PICK_OBJECT_PROPERTIES_PREDICATE: DeleteObjectPropertiesPredicate<any, any> = (_, key: any, __, keys?: any[]) =>
keys?.includes(key) ?? true
export const REGEXP_LEFT_SQUARE_BRACKET_WITHOUT_LEADING_DOT: RegExp = /([^.])\[/g
export const REGEXP_SQUARE_BRACKETS: RegExp = /[\[\]]/g

Expand Down
16 changes: 16 additions & 0 deletions src/definitions/interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ export interface AracnaFileJSON extends AracnaBlobJSON {
webkitRelativePath: string
}

export interface CloneObjectOptions {
deep: boolean
}

export interface CookieItem extends Record<PropertyKey, Primitive> {}

export interface CookieObject extends Record<string, string> {}
Expand Down Expand Up @@ -50,6 +54,10 @@ export interface DecodeBase32HexOptions extends DecodeBase32Options {}
export interface DecodeBase64Options extends DecodeBase16Options {}
export interface DecodeBase64URLOptions extends DecodeBase64Options {}

export interface DeleteObjectPropertiesOptions {
deep: boolean
}

export interface DeserializeBlobOptions {
resolveArrayBuffer?: boolean
resolveText?: boolean
Expand Down Expand Up @@ -148,6 +156,14 @@ export interface NodeFetch {
Response: any
}

export interface OmitObjectPropertiesOptions {
deep: boolean
}

export interface PickObjectPropertiesOptions {
deep: boolean
}

export interface RestApiConfig<T = unknown> extends FetchRequestInit<T> {
query?: object | string
status?: {
Expand Down
31 changes: 26 additions & 5 deletions src/definitions/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,25 @@ import type { AsyncStorage } from '../classes/async-storage.js'
import type { SyncStorage } from '../classes/sync-storage.js'
import type { Typeahead } from '../classes/typeahead.js'

export type ArrayIncludes<T> = (array: T[], item: T) => boolean
export type ArrayRemoves<T> = (array: T[], item: T) => boolean

export type DebounceMapKey = bigint | number | string | symbol | Function
export type DebounceMapValue = NodeJS.Timeout | number

export type DeleteObjectPropertiesPredicate<T extends object = object, K extends keyof T | string = keyof T | string> = (
object: T,
key: K,
value: T extends Record<K, infer V> ? V : unknown,
keys?: PropertyKey[]
) => boolean

export type DeserializeURLSearchParamsType = 'array' | 'object' | 'string'
export type SerializeURLSearchParamsType = 'string' | 'url-search-params'

export type EventEmitterEvents = Record<EventEmitterListenerName, EventEmitterListenerCallback>
export type EventEmitterListenerName = string | symbol
export type EventEmitterListenerCallback = (...args: any[]) => any

export type HasArrayItemPredicate<T> = (array: T[], item: T) => boolean

export type IntervalMapKey = bigint | number | string | symbol | Function
export type IntervalMapValue = NodeJS.Timeout | number

Expand All @@ -25,20 +31,35 @@ export type FetchRequestInfo = Request | string
export type GenerateRandomStringRandom = (bytes: number) => Uint8Array

export namespace KeyOf {
// export type Deep<T, D extends number = 16> = keyof T | Path<T, D>
export type Deep<T> = keyof T
// export type DeepArray<T, D extends number = 16> = ArrayPath<T, D>
export type DeepArray<T> = keyof T extends number ? keyof T : never
export type Shallow<T> = keyof T
export type ShallowArray<T> = keyof T extends number ? keyof T : never
}

export type LoggerLevel = 'verbose' | 'debug' | 'info' | 'warn' | 'error'
export type LoggerStatus = 'off' | 'on'

export type OmitObjectPropertiesPredicate<T extends object = object, K extends keyof T | string = keyof T | string> = (
object: T,
key: K,
value: T extends Record<K, infer V> ? V : unknown,
keys?: PropertyKey[]
) => boolean

export type PickObjectPropertiesPredicate<T extends object = object, K extends keyof T | string = keyof T | string> = (
object: T,
key: K,
value: T extends Record<K, infer V> ? V : unknown,
keys?: PropertyKey[]
) => boolean

export type Primitive = bigint | boolean | null | number | string | symbol | undefined

export type ProcessEnvValue = string | undefined

export type RemoveArrayItemsPredicate<T> = (array: T[], item: T, items?: T[]) => boolean

export type RequestMethod = 'CONNECT' | 'DELETE' | 'GET' | 'HEAD' | 'OPTIONS' | 'PATCH' | 'POST' | 'PUT' | 'TRACE'

export type StatusTransformer = (keys: string[]) => string
Expand Down
10 changes: 10 additions & 0 deletions src/functions/cafs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { tcp } from './tcp.js'

/**
* The `cafs` function stands for `call async functions sequentially`. It executes a list of async functions in sequence.
*/
export async function cafs(...fns: ((...args: any[]) => Promise<any>)[]): Promise<void> {
for (let fn of fns) {
await tcp(() => fn())
}
}
13 changes: 13 additions & 0 deletions src/functions/cafsue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { tcp } from './tcp.js'

/**
* The `cafsue` function stands for `call async functions sequentially until error`. It executes a list of async functions in sequence, the execution stops if a function throws or returns an error.
*/
export async function cafsue(...fns: ((...args: any[]) => Promise<any>)[]): Promise<void> {
let output: unknown | Error

for (let fn of fns) {
output = await tcp(() => fn())
if (output instanceof Error) return
}
}
18 changes: 18 additions & 0 deletions src/functions/cafsueof.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { tcp } from './tcp.js'

/**
* The `cafsueof` function stands for `call async functions sequentially until error or falsy`. It executes a list of async functions in sequence, the execution stops if a function throws or returns an error or a falsy value.
*/
export async function cafsueof(...fns: ((...args: any[]) => Promise<any>)[]): Promise<boolean> {
let output: boolean | Error

for (let fn of fns) {
output = await tcp(() => fn())
if (output instanceof Error) return false

output = Boolean(output)
if (!output) return false
}

return true
}
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,9 @@ export type {
} from './definitions/interfaces.js'
export * from './definitions/stubs.js'
export type * from './definitions/types.js'
export * from './functions/cafs.js'
export * from './functions/cafsue.js'
export * from './functions/cafsueof.js'
export * from './functions/debounce.js'
export * from './functions/gql.js'
export * from './functions/ma.js'
Expand Down
Loading

0 comments on commit 3049f17

Please sign in to comment.