@arpansaha13/utils
v0.9.0
Published
A personal collection of utils.
Downloads
247
Maintainers
Readme
Utilities
This package is a compilation of some utility functions that might be needed in general. Some of them are taken from different documentations and articles, and then modified.
Published as @arpansaha13/utils on npm.
General utilities
classNames
- Alias:
cn
A shorthand for twMerge(clsx(...classes)).
classNames('mx-auto max-w-7xl p-4', primary ? 'bg-indigo-600 text-white' : 'bg-transparent text-gray-900')Note:
clsxis imported from clsx/lite.
deepFreeze
Recursively freezes every non-primitive property of an object, preventing modifications to its properties.
const frozenObject = deepFreeze({ a: 1, b: { c: 2 } })
// frozenObject.a = 2; // Error: Cannot assign to read-only property 'a'isNullOrUndefined
Check if a value is null or undefined.
if (!isNullOrUndefined(variable)) {
// do something
}random
Generates a random number between the given min and max values.
random(5, 10)slugify
slugify('Hello, World!')
// Expected output: "hello-world"
slugify('Hello, Universe!', '_')
// Expected output: "hello_universe"trim
Removes leading, trailing, and extra whitespace in between a string.
const trimmedString = trim(' Hello, world! ')
// trimmedString === "Hello, world!"clamp
Limits a number to a specified range.
const clampedNumber = clamp(10, 0, 5)
// clampedNumber === 5truncate
Truncates a string to a specified length and adds an ellipsis.
const truncatedString = truncate('This is a long string', 10)
// truncatedString === "This is a..."hasLowerCase
Checks if a string contains at least one lowercase character.
const hasLowerCase = hasLowerCase('Hello')
// hasLowerCase === trueuint8ArrayToJson
Convert Uint8Array readable stream to json.
sanitize
Sanitize HTML by escaping special characters in a string.
nFormatter
Format a large number by adding suffixes like "k" and "M".
const formattedNumber = nFormatter(1234567, 2)
// formattedNumber === "1.23M"getOrdinalSuffix
Returns the appropriate ordinal suffix for that day (e.g., "st" for 1, "nd" for 2, "rd" for 3, and "th" for the rest).
Browser utilities
These utility functions are only meant to be used in the browser and will raise error if used in node.js environment.
getCookie
Returns the value of the cookie if it exists, else returns an empty string.
isTouchDevice
Detect whether the device has a touch screen.
Node utilities
These utility functions are only meant to be used in node.js environment and will raise error if used in the browser environment.
readJsonFile
A shorthand for JSON.parse(await readFile(path, 'utf8')).
readJsonFile('path/to/file')writeJsonFile
A shorthand for writeFile(path, JSON.stringify(json, null, 2)).
writeJsonFile('path/to/file', { ... })createEmptyFile
Creates an empty file. If the filePath already exists, an error is thrown.
createEmptyFile('path/to/file')