JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 82
  • Score
    100M100P100Q85753F
  • License Mit

This is A collection of commonly used frontend utility functions‌

Package Exports

  • core-fed-util

Readme

core-fed-util

This is A collection of commonly used frontend utility functions‌

Num

Description

Provides functions for number manipulation and arithmetic operations with precision.

Functions

  • getNthLargest(arr: number[], n: number): number | null

    • Returns the nth largest number in an array.
    • Params: arr (array of numbers), n (position)
    • Returns: nth largest number or null if n exceeds array length.
  • getDecimalPlaces(num: number): number

    • Returns the number of decimal places in a number.
    • Params: num (number)
    • Returns: count of decimal places.
  • addFloat(num1: number, num2: number): number

    • Adds two floating-point numbers with precision.
    • Params: num1, num2
    • Returns: sum with precision.
  • subtractFloat, multiplyFloat, divideFloat

    • Perform subtraction, multiplication, and division with precision similar to addFloat.
  • formatNumber(num: number): string

    • Formats a number with commas and two decimal places.
    • Params: num
    • Returns: formatted string.
  • convertNumberToDecimal(num: string): number

    • Converts a number string with commas to a decimal.
    • Params: num (string)
    • Returns: decimal number.
  • clampNumber(num: number, min: number, max: number): number

    • Clamps a number between a minimum and maximum value.
    • Params: num, min, max
    • Returns: clamped number.
  • convertNumberBase(number: number, base: number = 10): string

    • Converts a number to a different base (2-36).
    • Params: number, base
    • Returns: string representation in the new base.
  • isNumberInteger(num: number): boolean

    • Checks if a number is an integer.
    • Params: num
    • Returns: true if integer.
  • padNumber(num: number | string, padNum: number | string, length: number = 2): string

    • Pads a number with a specified character to a specified length.
    • Params: num, padNum, length
    • Returns: padded string.

Array

Description

Utility functions for array manipulation.

Functions

  • generateArrayNumbers(n: number, start: number = 1): number[]

    • Generates an array of numbers starting from a given number.
    • Params: n (length), start (starting number)
    • Returns: array of numbers.
  • flattenArray<T>(arr: T[], depth: number = 1): any[]

    • Flattens a nested array up to a specified depth.
    • Params: arr, depth
    • Returns: flattened array.
  • removeArrayDuplicates<T>(arr: T[], value: T): T[]

    • Removes duplicates of a specific value from an array.
    • Params: arr, value
    • Returns: array with duplicates removed.
  • findAllIndexes<T>(arr: T[], value: T): number[]

    • Finds all indexes of a value in an array.
    • Params: arr, value
    • Returns: array of indexes.
  • isEmptyArray<T>(arr: T[]): boolean

    • Checks if an array is empty.
    • Params: arr
    • Returns: true if empty.
  • sortArrayAscending(arr: number[]): number[]

    • Sorts an array in ascending order.
    • Params: arr
    • Returns: sorted array.
  • sortArrayDescending, bubbleArraySort

    • Sort in descending order and bubble sort implementation.
  • uniqueArray<T>(arr: T[]): T[]

    • Returns an array with unique values.
    • Params: arr
    • Returns: array of unique values.
  • omitArrayValues<T>(arr: T[], values: T[]): T[]

    • Removes specified values from an array.
    • Params: arr, values
    • Returns: filtered array.
  • arrayToMap(array: [string, any][]): Map<string, any>

    • Converts an array of key-value pairs to a Map.
    • Params: array
    • Returns: Map.
  • mergeArrays<T>(...arrays: T[][]): T[]

    • Merges multiple arrays into one.
    • Params: variable number of arrays
    • Returns: merged array.

Async

Description

Utilities for asynchronous operations.

Functions

  • sleep(ms: number): Promise<void>

    • Pauses execution for specified milliseconds.
    • Params: ms
    • Returns: Promise that resolves after delay.
  • executeAsyncFunctionsInOrder(functions: Function[]): Promise<AsyncResult[]>

    • Executes async functions in order.
    • Params: array of async functions
    • Returns: results array.
  • executeAsyncFunctionsConcurrently(functions: Function[]): Promise<any[]>

    • Runs async functions concurrently.
    • Params: array of async functions
    • Returns: results array.
  • runWithConcurrencyInLimit(tasks: Function[], maxConcurrency: number): Promise<any[]>

    • Runs tasks with concurrency limit.
    • Params: tasks, maxConcurrency
    • Returns: results array.
  • asyncify(fn: Function): Promise<(...args: any[]) => Promise<any>>

    • Converts a sync function to async.
    • Params: fn
    • Returns: async function wrapper.

Boolean

Description

Boolean value checking and manipulation.

Functions

  • checkAllTrue(...args: any[]): boolean

    • Checks if all arguments are truthy.
    • Params: variable arguments
    • Returns: true if all truthy.
  • checkAnyTrue, checkAllFalse, checkAnyFalse

    • Similar checks for any truthy, all falsy, any falsy.
  • classIf(condition: any, className: string): string

    • Returns class name if condition is true.
    • Params: condition, className
    • Returns: class name or empty string.
  • filterTruthyProps(obj: Record<string, any>): Record<string, any>

    • Filters object to include only truthy properties.
    • Params: obj
    • Returns: filtered object.
  • toBoolean(value: any): boolean

    • Converts value to boolean.
    • Params: value
    • Returns: boolean value.
  • isTrue(value: any): boolean, isFalse(value: any): boolean

    • Check if value is truthy or falsy.

Browser

Description

Browser-related utilities for URL and storage operations.

Functions

  • getUrlParam(name: string): string | null

    • Gets a URL parameter value.
    • Params: name
    • Returns: parameter value or null.
  • hasUrlParam(name: string): boolean

    • Checks if URL parameter exists.
    • Params: name
    • Returns: true if exists.
  • setUrlParam(name: string, value: string): void

    • Sets a URL parameter.
    • Params: name, value
  • removeUrlParam(name: string): void

    • Removes a URL parameter.
    • Params: name
  • getAllUrlParams(): Record<string, string>

    • Gets all URL parameters as an object.
    • Returns: object of parameters.
  • getCurrentUrlInfo(): { href, protocol, host, hostname, pathname, search, hash }

    • Returns current URL information.
    • Returns: URL components object.
  • detectDeviceType(): 'mobile' | 'tablet' | 'desktop'

    • Detects device type based on user agent.
    • Returns: device type string.
  • getBrowserType(): BrowserType

    • Detects browser type.
    • Returns: browser name.

StorageOperator Class

  • static setKey(key: string, value: object, expireHours: number = 24): void

    • Sets a value in localStorage with expiration.
    • Params: key, value, expireHours
  • static getKey(key: string): object | null

    • Gets a value from localStorage, respects expiration.
    • Params: key
    • Returns: value or null if expired.
  • static removeKey(key: string): void

    • Removes a key from localStorage.
    • Params: key

Date

Description

Date and time utility functions.

Functions

  • getCurrentLocalDateTime(): string

    • Gets current local date and time.
    • Returns: formatted string.
  • getSpecificLocalDateTime(date: Date): string

    • Gets specific local date and time.
    • Params: date
    • Returns: formatted string.
  • getCurrentLocalDate(): string, getCurrentLocalTime(): string

    • Get current date or time in specific formats.
  • getSpecificLocalDate(date: Date): string, getSpecificTime(date: Date): string

    • Get specific date or time in formats.
  • getUtcTime(): string

    • Gets current UTC time string.
    • Returns: UTC time string.
  • getFormatDate(date: Date, format: string = '-'): string

    • Formats date with custom separator.
    • Params: date, format
    • Returns: formatted date string.
  • getFormatTime(date: Date, format: string = ':'): string

    • Formats time with custom separator.
    • Params: date, format
    • Returns: formatted time string.
  • getSpecificDateTime(date: Date, formatDate: string = '-', formatTime: string = ':'): string

    • Combines formatted date and time.
    • Params: date, formatDate, formatTime
    • Returns: combined string.
  • getRelativeTime(date: Date): string

    • Returns relative time string (e.g., "2 days ago").
    • Params: date
    • Returns: relative time string.
  • dateDiff(date1: Date, date2: Date, unit: DateUnit): number

    • Calculates difference between two dates in specified unit.
    • Params: date1, date2, unit
    • Returns: difference value.
  • getFirstDayOfMonth(date: Date): Date

    • Gets first day of the month for a date.
    • Params: date
    • Returns: first day Date.
  • getLastDayOfMonth(date: Date): number

    • Gets last day of the month for a date.
    • Params: date
    • Returns: day number.

Dom

Description

DOM manipulation and interaction utilities.

Functions

  • getDomHeight(): number, getDomWidth(): number

    • Gets DOM height or width.
    • Returns: dimension value.
  • getViewportHeight(): number, getViewportWidth(): number

    • Gets viewport height or width.
    • Returns: dimension value.
  • getScrollTop(): number, getScrollLeft(): number

    • Gets scroll position.
    • Returns: scroll value.
  • mouseInElement(element: HTMLElement, x: number, y: number): boolean

    • Checks if coordinates are inside an element.
    • Params: element, x, y
    • Returns: true if inside.
  • mousePositioninElement(element: HTMLElement, event: MouseEvent): { x: number, y: number } | null

    • Gets mouse position relative to element.
    • Params: element, event
    • Returns: position object or null.
  • getMousePosition(event: MouseEvent): { x: number, y: number }

    • Gets mouse position in document.
    • Params: event
    • Returns: position object.
  • getRealElementHeight(element: HTMLElement): number, getElementRealWidth(element: HTMLElement): number

    • Gets real dimensions of an element including scroll.
    • Params: element
    • Returns: dimension value.
  • isElInViewport(el: HTMLElement): boolean

    • Checks if element is visible in viewport.
    • Params: el
    • Returns: true if visible.
  • removeElement(el: HTMLElement): void

    • Removes element from DOM.
    • Params: el
  • containSpecificEl(el: HTMLElement, child: HTMLElement): boolean

    • Checks if element contains a child.
    • Params: el, child
    • Returns: true if contains.
  • findAllChildElements(el: HTMLElement): HTMLElement[]

    • Finds all child elements of a given element.
    • Params: el
    • Returns: array of child elements.
  • hasChildElements(el: HTMLElement): boolean

    • Checks if element has child elements.
    • Params: el
    • Returns: true if has children.
  • documentHasFocus(): boolean

    • Checks if document has focus.
    • Returns: true if focused.
  • getElementPosition(el: HTMLElement): { top, left, width, height }

    • Gets element position and dimensions.
    • Params: el
    • Returns: position object.
  • addEventListener(target: HTMLElement, event: keyof HTMLElementEventMap, callback: () => void, options: AddEventListenerOptions = {}): void

    • Adds event listener with browser compatibility.
    • Params: target, event, callback, options
  • downloadFile(data: any, fileName: string): void

    • Downloads data as a file.
    • Params: data, fileName
  • downloadImage(imgElement: HTMLImageElement, fileName: string): void

    • Downloads image from element.
    • Params: imgElement, fileName
  • downloadImageByUrl(imgUrl: string, fileName: string): void

    • Downloads image by URL.
    • Params: imgUrl, fileName
  • uploadFile(fileInput: HTMLInputElement, callback: (data: string, fileName: string) => void): void

    • Uploads file and calls callback with data.
    • Params: fileInput, callback
  • copyToClipboard(text: string): Promise<boolean>

    • Copies text to clipboard.
    • Params: text
    • Returns: Promise indicating success.
  • readFromClipboard(): Promise<string>

    • Reads text from clipboard.
    • Returns: Promise with clipboard text.

Env

Description

Environment detection utilities.

Functions

  • isReactEnv(): boolean, isVueEnv(): boolean, isAngularEnv(): boolean, isSvelteEnv(): boolean, isPreactEnv(): boolean, isSolidEnv(): boolean

    • Check if current environment is a specific framework environment.
    • Returns: true if framework is detected.
  • isNodeEnv(): boolean

    • Checks if environment is Node.js.
    • Returns: true in Node.js.
  • isMobile(): boolean

    • Checks if browser is on a mobile device.
    • Returns: true if mobile.
  • curBrowser(): BrowserName

    • Gets current browser name.
    • Returns: browser name string.
  • hasGlobalVariable(variable: string | number): boolean

    • Checks if a global variable exists.
    • Params: variable
    • Returns: true if exists.

Function

Description

Function utilities for execution control and composition.

Functions

  • retryFn(fn: () => Promise<any>, maxAttempts: number = 3, delay: number = 1000): Promise<any>

    • Retries an async function with exponential backoff.
    • Params: fn, maxAttempts, delay
    • Returns: Promise with result.
  • TimedFn(fn: (...args: any[]) => any): (...args: any[]) => any

    • Decorator to log function execution time.
    • Params: fn
    • Returns: wrapped function.
  • onceFn(fn: Function): (...args: any[]) => any

    • Ensures a function is executed only once.
    • Params: fn
    • Returns: controlled function.
  • memoizeFn(fn: Function): (...args: any[]) => any

    • Memoizes function results based on arguments.
    • Params: fn
    • Returns: memoized function.
  • pipeFn(...fns: Function[]): (value: any) => any

    • Creates a pipeline of functions.
    • Params: functions array
    • Returns: pipeline function.
  • curryFn(fn: Function): (...args: any[]) => any

    • Curries a function for partial application.
    • Params: fn
    • Returns: curried function.

Is

Description

Type checking utilities.

Functions

  • isType(value: unknown, type: string): boolean

    • Checks if value is of a specific type.
    • Params: value, type
    • Returns: true if matches.
  • Type-specific checks: isNumber, isString, isArray, isObject, isFunction, isBoolean, isNull, isUndefined, isDate, isRegExp, isSymbol, isBigInt, isError, isDateTime, isMap, isSet, isWeakMap, isWeakSet, isPromise, isElement

    • Each checks for their respective types.
    • Params: value
    • Returns: true if matches.

Json

Description

JSON data manipulation utilities.

Functions

  • flattenJsonObject(obj: Record<string, any>, prefix: string = '', result: Record<string, any> = {}): Record<string, any>

    • Flattens nested JSON object.
    • Params: obj, prefix, result
    • Returns: flattened object.
  • unFlattenJsonObject(obj: Record<string, any>, separator: string = '.'): Record<string, any>

    • Unflattens JSON object.
    • Params: obj, separator
    • Returns: nested object.
  • getJsonObjectDiff(obj1: Record<string, any>, obj2: Record<string, any>): Record<string, { oldValue: any, newValue: any }>

    • Gets differences between two JSON objects.
    • Params: obj1, obj2
    • Returns: differences object.
  • renameJsonObject(obj: Record<string, any>, renameMap: Record<string, string>): Record<string, any>

    • Renames keys in JSON object.
    • Params: obj, renameMap
    • Returns: renamed object.
  • jsonToQueryString(obj: Record<string, any>, prefix: string = ''): string

    • Converts JSON to query string.
    • Params: obj, prefix
    • Returns: query string.

Log

Description

Logging utility with different levels and styling.

Logger Class

  • constructor(name: string = 'global', level: LogLevel = LogLevel.DEBUG)

    • Initializes logger with name and level.
    • Params: name, level
  • setLevel(level: LogLevel): void

    • Sets logging level.
    • Params: level
  • debug(...args: any[]): void, info(...args: any[]): void, warn(...args: any[]): void, error(...args: any[]): void

    • Log messages at different levels.
    • Params: variable arguments
  • time(label: string): () => void

    • Starts a timer and returns a stop function.
    • Params: label
    • Returns: stop function that logs duration.

Map

Description

Map utility functions.

Functions

  • safeGetMapValue<K, V>(map: Map<K, V>, key: K, defaultVal: V | undefined): V | undefined

    • Safely gets a value from a Map with default.
    • Params: map, key, defaultVal
    • Returns: value or default.
  • mapToObject(map: Map<string, any>): Record<string, any>

    • Converts Map to plain object.
    • Params: map
    • Returns: object.
  • mapToArray<K, V>(map: Map<K, V>): [K, V][]

    • Converts Map to array of entries.
    • Params: map
    • Returns: array.
  • areMapsEqual<K, V>(map1: Map<K, V>, map2: Map<K, V>): boolean

    • Checks if two Maps are equal.
    • Params: map1, map2
    • Returns: true if equal.
  • mergeMaps<K, V>(...maps: Map<K, V>[]): Map<K, V>

    • Merges multiple Maps.
    • Params: variable Maps
    • Returns: merged Map.

Math

Description

Mathematical utility functions.

Functions

  • getRandomInt(min: number, max: number): number

    • Gets random integer between min and max.
    • Params: min, max
    • Returns: random integer.
  • getRandomFromArray<T>(array: T[]): T

    • Gets random element from array.
    • Params: array
    • Returns: random element.
  • getInteger(num: number): number

    • Gets integer part of a number.
    • Params: num
    • Returns: integer value.
  • getFloat(num: number): number

    • Gets decimal part of a number.
    • Params: num
    • Returns: decimal value.
  • radianToAngle(radian: number): number, angleToRadian(angle: number): number

    • Converts between radians and degrees.
    • Params: value in respective unit
    • Returns: converted value.
  • getRadian(x: number, y: number, centerX: number, centerY: number): number

    • Gets radian between point and circle center.
    • Params: coordinates
    • Returns: radian value.

Obj

Description

Object manipulation utilities.

Functions

  • objDeepClone<T>(target: Record<string | number, any> | T[]): Record<string | number, any> | T[]

    • Deep clones an object or array.
    • Params: target
    • Returns: clone.
  • objShallowClone<T>(target: object | T[]): object | T[]

    • Shallow clones an object or array.
    • Params: target
    • Returns: clone.
  • isEqual(obj1: Record<string, any>, obj2: Record<string, any>): boolean

    • Checks deep equality of two objects.
    • Params: obj1, obj2
    • Returns: true if equal.
  • objInheritPrototype(child: any, parent: any): void

    • Inherits prototype from parent to child.
    • Params: child, parent
  • isEmptyObject(obj: object): boolean

    • Checks if object is empty.
    • Params: obj
    • Returns: true if empty.
  • objPick(obj: Record<string, any>, keys: (string | number)[]): Record<string, any>

    • Picks specific keys from object.
    • Params: obj, keys
    • Returns: picked properties object.
  • objOmit(obj: Record<string, any>, keys: (string | number)[]): Record<string, any>

    • Omits specific keys from object.
    • Params: obj, keys
    • Returns: omitted properties object.
  • objToQueryString(obj: object): string

    • Converts object to query string.
    • Params: obj
    • Returns: query string.
  • objectToMap(obj: Record<string, any>): Map<string, any>

    • Converts object to Map.
    • Params: obj
    • Returns: Map.
  • mergeObjects<T extends Record<string, any>>(...objects: T[]): T

    • Merges multiple objects.
    • Params: variable objects
    • Returns: merged object.
  • freezeObject<T extends Record<string, any>>(obj: T): Readonly<T>

    • Recursively freezes an object.
    • Params: obj
    • Returns: frozen object.
  • freezeObjectShallow<T extends Record<string, any>>(obj: T): Readonly<T>

    • Freezes object shallowly.
    • Params: obj
    • Returns: frozen object.
  • freezeObjectPickKeys<T extends Record<string, any>>(obj: T, keys: (string | number)[]): void

    • Freezes specific keys of an object.
    • Params: obj, keys

Proxy

Description

Proxy creation utilities for object control.

Functions

  • createValidatorProxy<T extends object>(target: T, validator: Validator): T

    • Creates a proxy that validates property assignments.
    • Params: target, validator
    • Returns: proxy object.
  • createReadonlyProxy<T extends object>(target: T): T

    • Creates a read-only proxy.
    • Params: target
    • Returns: read-only proxy.
  • createObservableProxy<T extends object>(target: T, onChange: (prop: string | symbol, value: any) => void): T

    • Creates a proxy that notifies on changes.
    • Params: target, onChange
    • Returns: observable proxy.
  • createCallFnAspectProxy(target: Function, callFn: (prop: string | symbol, args: any[]) => void, before: boolean = true): Function

    • Creates a proxy for function call interception.
    • Params: target, callFn, before
    • Returns: proxy function.
  • withPrivatePropsProxy<T extends object>(target: T, privateProps: (string | symbol)[]): T

    • Creates a proxy with private properties.
    • Params: target, privateProps
    • Returns: proxy with access control.

Regexp

Description

Regular expression validation utilities.

Functions

  • validEmail(email: string): boolean

    • Validates email format.
    • Params: email
    • Returns: true if valid.
  • validPassword(password: string): boolean

    • Validates password strength (8+ chars, mixed case, digits).
    • Params: password
    • Returns: true if valid.
  • validIdCard(idCard: string): boolean

    • Validates ID card number format.
    • Params: idCard
    • Returns: true if valid.
  • validateURL(url: string): boolean

    • Validates URL format.
    • Params: url
    • Returns: true if valid.
  • validateFormatDate(date: string, format: string): boolean

    • Validates date string against format (e.g., 'YYYY-MM-DD').
    • Params: date, format
    • Returns: true if valid.

Request

Description

HTTP request utilities using XMLHttpRequest.

Functions

  • getRequest(url: string, params: object = {}): Promise<any>

    • Makes a GET request.
    • Params: url, params
    • Returns: Promise with response.
  • postRequest(url: string, data: object): Promise<any>

    • Makes a POST request.
    • Params: url, data
    • Returns: Promise with response.
  • delRequest(url: string, params: object = {}): Promise<any>

    • Makes a DELETE request.
    • Params: url, params
    • Returns: Promise with response.
  • putRequest(url: string, data: object): Promise<any>

    • Makes a PUT request.
    • Params: url, data
    • Returns: Promise with response.

Set

Description

Set operations utilities for arrays.

Functions

  • uninonSet<T>(...args: T[][]): T[]

    • Computes union of multiple arrays.
    • Params: variable arrays
    • Returns: union array.
  • intersectionSet<T>(...args: T[][]): T[]

    • Computes intersection of multiple arrays.
    • Params: variable arrays
    • Returns: intersection array.
  • differenceSet<T>(arr1: T[], arr2: T[]): T[]

    • Computes difference between two arrays.
    • Params: arr1, arr2
    • Returns: difference array.
  • symmetricDifferenceSet<T>(arr1: T[], arr2: T[]): T[]

    • Computes symmetric difference between two arrays.
    • Params: arr1, arr2
    • Returns: symmetric difference array.
  • isSubset<T>(arr1: T[], arr2: T[]): boolean

    • Checks if one array is a subset of another.
    • Params: arr1, arr2
    • Returns: true if subset.
  • isSuperset<T>(arr1: T[], arr2: T[]): boolean

    • Checks if one array is a superset of another.
    • Params: arr1, arr2
    • Returns: true if superset.
  • mapSet<T, U>(arr: Set<T>, callback: (item: T) => U): U[]

    • Maps a Set to an array using a callback.
    • Params: arr, callback
    • Returns: mapped array.

String

Description

String manipulation utilities.

Functions

  • truncateStr(str: string, maxLen: number, suffix: string = '...'): string

    • Truncates string to maximum length with suffix.
    • Params: str, maxLen, suffix
    • Returns: truncated string.
  • camelToKebab(str: string): string

    • Converts camelCase to kebab-case.
    • Params: str
    • Returns: converted string.
  • kebabToCamel(str: string): string

    • Converts kebab-case to camelCase.
    • Params: str
    • Returns: converted string.
  • escapeHTML(str: string): string

    • Escapes HTML characters in a string.
    • Params: str
    • Returns: escaped string.
  • unescapeHTML(str: string): string

    • Unescapes HTML characters in a string.
    • Params: str
    • Returns: unescaped string.
  • isValieUrl(url: string): boolean

    • Validates if a string is a valid URL.
    • Params: url
    • Returns: true if valid.
  • capitalizeStr(str: string): string

    • Capitalizes the first character of a string.
    • Params: str
    • Returns: capitalized string.
  • countOccurrences(str: string, char: string): number

    • Counts occurrences of a character in a string.
    • Params: str, char
    • Returns: count.
  • encodebase64(str: string): string

    • Encodes string to base64.
    • Params: str
    • Returns: base64 string.
  • decodebase64(str: string): string

    • Decodes base64 string.
    • Params: str
    • Returns: decoded string.
  • generateRandomString(length: number = 10, chars: string = 'A-Za-z0-9'): string

    • Generates a random string.
    • Params: length, chars
    • Returns: random string.
  • trimString(str: string): string

    • Trims whitespace from string.
    • Params: str
    • Returns: trimmed string.

This documentation covers all the provided modules in the Core-Fed-Util library. Each function and class is designed to simplify common programming tasks and improve code readability and maintainability.