@kreisler/js-helpers
A comprehensive JavaScript/TypeScript library that provides a collection of utility functions to eliminate code repetition. This package includes helpers for string manipulation, data conversion, text formatting, API creation, error handling, and much more.Installation
Core Functions
String Normalization
normalize()
Normalizes a string by removing or replacing special characters and accents.The string to normalize
If true, replaces special characters with normalized equivalents. If false, removes them and converts to URL-friendly format.
string - The normalized string
trimText()
Removes excessive whitespace and newlines from text.The string to trim
string - The trimmed string
stripHtmlTags()
Removes HTML tags from a string.The string containing HTML tags
Custom regex pattern for matching HTML tags
string - The string without HTML tags
String Similarity
levenshteinDistance()
Calculates the Levenshtein distance between two strings (the minimum number of single-character edits required to change one string into another).titleSimilarity()
Calculates the similarity between two titles (returns a value between 0 and 1, where 1 is identical).The first title to compare
The second title to compare
number - Similarity score between 0 and 1
A threshold of 0.8 is recommended for determining if titles are similar enough
Number Formatting
abbreviateNumber()
Abbreviates large numbers with k, M, B, or T suffixes.The number to abbreviate
string - The abbreviated number
Byte Conversion Functions
Convert bytes to larger units with customizable decimal precision.Function Signatures
Function Signatures
Base64 Converters
Encode and decode UTF-8 strings to/from Base64.Converts a UTF-8 string to Base64 encoding
Decodes a Base64 string to UTF-8
Unit Converters
Convert between different units of measurement.Available Converter Functions
Available Converter Functions
Converts Kelvin to Fahrenheit
Converts Kelvin to Celsius
Converts meters per second to miles per hour
Converts meters per second to kilometers per hour
WhatsApp Markdown Formatting
TheMarkdownWsp object provides functions to format text for WhatsApp.
WhatsApp supports the following formatting:
- Bold:
*text* - Italic:
_text_ Strikethrough:~text~- Monospace:
```text``` - Quote:
> text - Bulleted List:
- textor* text - Numbered List:
1. text
Command-Line Argument Parser
argv2Object()
Converts command-line arguments to a key-value object. Supports both simplekey=value format and Unix-style options.
Array of command-line arguments to parse
Whether to parse Unix-style command-line options (e.g.,
-h, --name=value, --is-admin)Debounce Function
Create debounced functions with advanced features like immediate execution, callbacks, and flood protection.Debounce Options
Debounce Options
The function to debounce
Milliseconds to wait before calling the function
Configuration object with optional callbacks:
immediate(boolean): Execute immediately on first callonCall(Function): Called when debounce function is invokedonComplete(Function): Called when debounce execution completesflood(number): Number of calls before triggering onFloodonFlood(Function): Called when flood limit is reached
API Client Creator
createApi()
Creates a dynamic API client using JavaScript Proxy. Build type-safe API clients with automatic URL construction.Define your API interface
Create a TypeScript interface that describes your API endpoints and their parameters.
createApi Options
createApi Options
Base URL for the API
Optional RequestInit configuration with additional options:
x_debug: Enable debug mode (returns request info instead of making the call)x_json: Force JSON response parsing (default)x_text: Force text response parsingx_response: Return raw Response object
Try-Catch Helpers
Simplify error handling with Go-style error handling patterns.The try-catch helpers return a tuple
[error, result] where:- If successful:
[null, result] - If error occurs:
[Error]
TypeScript Support
This package is written in TypeScript and includes complete type definitions. All functions have proper type signatures and JSDoc comments for excellent IDE support.API Reference Summary
String Manipulation
String Manipulation
normalize(str, urls?)- Normalize strings and remove special characterstrimText(str)- Remove excessive whitespacestripHtmlTags(str, exp?)- Remove HTML tagslevenshteinDistance(a, b)- Calculate edit distancetitleSimilarity(title1, title2)- Calculate title similarity (0-1)
Number & Unit Conversion
Number & Unit Conversion
abbreviateNumber(number)- Abbreviate large numbers (k, M, B, T)bytes2Kb(size, decimal?)- Convert bytes to KBbytes2Mb(size, decimal?)- Convert bytes to MBbytes2Gb(size, decimal?)- Convert bytes to GBconverters.kToF(k, precision?)- Kelvin to Fahrenheitconverters.kToC(k, precision?)- Kelvin to Celsiusconverters.msToMph(speed, precision?)- m/s to mphconverters.msToKmh(speed, precision?)- m/s to km/h
Encoding & Data
Encoding & Data
base64converters.utf8Tob64(str)- Encode UTF-8 to Base64base64converters.b64Toutf8(str)- Decode Base64 to UTF-8argv2Object(argv, unixmode?)- Parse command-line arguments
Text Formatting
Text Formatting
MarkdownWsp.Bold(text)- Format as boldMarkdownWsp.Italic(text)- Format as italicMarkdownWsp.Strikethrough(text)- Format as strikethroughMarkdownWsp.Monospace(text)- Format as monospaceMarkdownWsp.InlineCode(text)- Format as inline codeMarkdownWsp.Quote(text)- Format as quoteMarkdownWsp.BulletedList(items, bullet?)- Create bulleted listMarkdownWsp.NumberedLists(items)- Create numbered list
Utilities
Utilities
debounce(func, msWait, fns?)- Create debounced functioncreateApi<T>(url, args?)- Create dynamic API clientTCatch.tryCatch(fn, ...args)- Synchronous try-catch wrapperTCatch.tryCatchPromise(fn, ...args)- Async try-catch wrapper