power-helper
v0.9.1
Published
This is javascript tool collection, is your super power helper.
Downloads
2,383
Maintainers
Readme
Power Helper is a lightweight JavaScript utility toolkit that integrates a wide variety of tools. It is clean, requires no dependencies, and can be seen as a more feature-rich alternative to Lodash. It supports virtually all JavaScript environments.
During development, we follow these principles to provide the best developer experience:
- Full test coverage to ensure product reliability.
- Comprehensive documentation to help users get started quickly.
- Continuous improvement of code quality for maintainability and extensibility.
- Complete editor hints for a more efficient development workflow.
- Full TypeScript support for a better development experience.
Installation
npm
npm install power-helperyarn
yarn add power-helperHow to Use
PowerHelper is divided into three sections:
Utils
Mostly composed of pure functions.
calc - A utility for calculations.
- toMs - Converts a time value in a specified format to milliseconds.
array - Elegant array operations.
- check - Adds a value to an array if it doesn't exist, or removes it if it does.
- unique - Removes duplicate elements from an array.
- groups - Groups array elements into chunks of a specified size.
- asyncMap - An async-compatible map function.
- randomPick - Picks a random value from an array.
- randomPicks - Picks a specified number of unique random values from an array. Returns the entire array if the count exceeds its length.
detect - Detects the current runtime environment.
- inAppBrowser - Checks if running inside an in-app browser. Coverage is limited; for reference only.
- inMobile - Checks if running on iOS or Android.
- inIOS - Checks if running on iOS.
- inAndroid - Checks if running on Android.
- inSafari - Checks if running in the Safari browser.
flow - Flow control utilities.
- run - Immediately invokes a function and returns its result.
- sleep - Pauses execution for a specified duration (in milliseconds).
- randomInt - Returns a random integer within a specified range.
- createUuid - Generates a random v4 UUID.
- createWithTsUuid - Generates a random v4 UUID prefixed with the current timestamp (ms).
- retry - Elegantly retries an operation a limited number of times until it succeeds.
- asyncWhile - An async loop combining asynchronous execution with a counter.
- waitFor - A flow control utility for waiting on a condition.
json - Elegant JSON format handling.
- jpjs - The classic deep clone:
JSON.parse(JSON.stringify(data)). - nonStrictJSONParse - Runs JSON.parse; returns
{}on failure. - nonStrictJSONStringify - Runs JSON.stringify; returns
'{}'on failure.
text - String-related utilities.
- headMatch - Checks if text starts with the target.
- lastMatch - Checks if text ends with the target.
- byteLength - Gets the byte length of the specified text.
- replaceVar - Replaces named variables in a text string.
- format - Formats text into a specified pattern, using
vas the mapped value placeholder. - findMatchOrLast - Constrains text to a set of options; returns the last option if none match.
- pickInTagContents - Extracts only the content within specified tags from text.
- removeInTagContents - Removes only the content within specified tags from text.
pick - Precisely extract target values.
- ifBad - Returns a default value if the value is
null | undefined | Error | NaN. - ifEmpty - Returns a default value if the value is
null | undefined. - getType - Returns a more precise type than
typeof. - peel - Gets the value at a specified path; returns
nullif not found. - vars - Gets the list of variables found within a string.
checker - Data validators.
- inputAccept - Checks whether a file matches the format specified by an input tag's
acceptattribute.
element - Elegant DOM operations.
- importScript - Injects a JavaScript tag at runtime. Browser only.
- importCss - Injects a stylesheet link tag at runtime. Browser only.
- createAndAppend - Creates a tag and appends it to the specified element. Browser only.
record - Elegant object operations.
- omit - Shallow-copies an object while omitting specified keys.
- simpleCheckDeepDiff - Simply checks if two objects differ; returns
trueif they do. Supports all JSON-compatible types. - setMapValue - Copies values from a source object onto a target object and returns a new object.
- createStrictObject - Creates a strictly validated, translated, and immutable object. Typically used for environment variables.
- promiseAllWithKeys - A key-value pair version of
Promise.all.
Modules
More powerful composite tools.
Log - A more flexible logging utility.
Hook - Async-based event system.
I18n - Multi-language operation system.
Once - An async event that executes only once.
Pool - A data pool for easily making requests and caching response data.
Cache - Caches request results for specified parameters with an expiration time.
Asset - A resource loading tool for initializing required static assets.
Event - A simple event emitter for listening to and triggering events.
Timer - A timer that can count up or count down.
Ticker - Works like setInterval (and actually is), but allows multiple event listeners.
Loader - A loading component that collects and dispatches multiple promises.
Debounce - Debounce functionality that collects results and delays execution after an event fires, preventing frequent requests.
Resource - A more elegant way to fetch various static resources.
Schedule - Creates multiple scheduled execution systems with guaranteed non-overlapping runs.
Reactive - Listens for object changes via polling.
JobsQueue - Limited batch job execution.
Exception - An advanced error message handling tool.
CacheLite - Synchronous key-value access, similar to Map but with TTL support.
Breakpoint - A viewport breakpoint detection tool.
Interaction - Builds listenable, trackable, and visualizable message integration tools.
StyleString - A tool for conveniently composing HTML element style strings.
LocalStorage - Helps you operate LocalStorage more safely in complex web applications.
AsyncLocalStorage - Async LocalStorage operations to support more usage patterns.
PromiseOverlap - Controls multiple identical promise calls to return only the first or the last result.
QueryCollection - Collects data within a time window and dispatches it all at once.
WebSocketClient - A WebSocket module with reconnection and channel support. Listen to server messages via onMessage and broadcast to other listeners via the event system.
ElementListenerGroup - Elevates element addEventListener to a more manageable level.
PreloadPort - Preloads data and passes it to consumers by ID.
Types
Encapsulates complex type patterns to improve development safety and efficiency.
import { TDate, TPick, TRecord, TString } from 'power-helper'Types are a convenient wrapper for module development. For more powerful type expressions, consider the following packages:
Versions
0.6.0
- [Added] - WebSocket adds
keepAliveconnection persistence. - [Fixed] - Standardized Event channel naming.
- [Fixed] -
job-queuesrenamed tojobs-queue. - [Improved] - Documentation improvements.
0.7.0
We adjusted the build format and documentation to optimize the overall developer experience.
Breaking Changes
- CacheLite -
expTimeparameter renamed tottl. - Cache -
keepAliveparameter renamed tottl.
0.8.0
Switched to ES Module import style.
