This is a JavaScript library that is a collection of features that I wish vanilla JavaScript had to streamline production. Features range from efficient math functions to string utilities to advanced type detection. This was first made as a personal library, but then I just decided to give it a home.
lib.randomNumber(min, max)
generates a random integer betweenmin
andmax
. Inclusive. Note that this function is not cryptographically secure.lib.coinToss()
returns eithertrue
orfalse
randomly. Note that this function is not cryptographically secure.lib.clamp(value, min, max)
returnsvalue
clamped betweenmin
andmax
. Inclusive.lib.lerp(start, end, amount)
performs linear interpolation onstart
andend
, based on the weighting factor,amount
.lib.map(value, inMin, inMax, outMin, outMax)
maps value from the input range defined byinMin
andinMax
to the output range defined byoutMin
andoutMax
. IfinMin === inMax
, the function will result in a division by zero.lib.areaOfCircleByRadius(radius)
returns the area of a circle given its radius. Uses the formula π * r².lib.areaOfCircleByDiameter(diameter)
returns the area of a circle given its diameter. Internally converts diameter to radius and applies the formula π * r².lib.circumferenceOfCircleByRadius(radius)
returns the circumference of a circle given its radius. Uses the formula 2 * π * r.lib.circumferenceOfCircleByDiameter(diameter)
returns the circumference of a circle given its diameter. Uses the formula π * d.
lib.stringIsEmpty(string)
returnstrue
if the string is empty (""
), and false otherwise.lib.capitalizeFirstLetterOfString(string)
returnsstring
, but with the first letter of the string capitalized. For example,"example string"
would result in"Example string"
.lib.slugify(string)
altersstring
into a human-readable URL slug. The full process:- Normalize Unicode
- Remove diatrics
- String to lowercase
- Trim whitespace at start and end
- Replace spaces with hyphens
- Replace non-word characters except for hyphens
- Replace multiple hyphens with one
lib.validJSON(string)
returnstrue
ifstring
is valid JSON, otherwise returnsfalse
.lib.copyTextToClipboard(string)
(async function) copiesstring
as text to the clipboard, returning aPromise
that is resolved when the clipboard has been updated. Needs"clipboardRead"
or"clipboardWrite"
permissions and only works in secure contexts.lib.readClipboardAsText()
(async function) returns a string of the textual contents of the clipboard. Returns an empty string if the clipboard is empty or does not contain text. Needs"clipboardRead"
or"clipboardWrite"
permissions and only works in secure contexts.lib.getLetterOfAlphabet(position)
returns the letter of the alphabet atposition
(zero-indexed, range is 0-25) as a string.lib.randomString(length, randomCase, numbers)
returns random sequences of letters (eg,hfekjlnoxl
ifrandomCase
isfalse
, orQENtbUFmnz
ifrandomCase
istrue
) with numbers ifnumbers
is true, otherwise with no numbers. Default values for bothrandomCase
andnumbers
arefalse
. `Note that this function is not cryptographically secure.
lib.objectIsEmpty(object)
returns true ifobject
has no properties, returns false otherwise.lib.objectPropertiesLength(object)
returns the number of enumerable properties inobject
as a number.lib.isPlainObject(object)
determines whetherobject
is a plain object (i.e., not an array, function, or other built-in type).lib.cleanObject(object)
returnsobject
that has removed null, undefined, or empty values.lib.falsy(value)
determines ifvalue
is falsy, returning eitherfalse
ortrue
.
lib.isLeapYear(year)
returns true ifyear
is a leap year, returns false otherwise.lib.daysInMonth(month, year)
returns the days inmonth
as a number.year
is needed to account for leap years.
lib.unique(array)
returns a new array with only the unique elements from the input array, removing any duplicates.
lib.getFile()
(async function) shows the file picker, then when the user selects a file, it returns aFile
object. Will not work in Safari, Firefox, Webview, Samsung Internet, and Deno. Requires a secure context.lib.getFileWithOpts(options)
(async function) shows the file picker configured byoptions
, then when the user selects a file, it returns aFile
object. Refer to Mozilla docs for configuring the file picker: here. Ifoptions
is not defined, an error is returned. Will not work in Safari, Firefox, Webview, Samsung Internet, and Deno. Requires a secure context.
lib.batteryIsCharging()
(async function) returns aBoolean
value,true
if the device is charging, andfalse
otherwise. Will not work in Safari, Firefox and Webview. Requires a secure context.lib.batteryLevel()
(async function) returns the level of the device's battery between0.0
(fully discharged) and1.0
(completely charged), as aNumber
. Will not work in Safari, Firefox and Webview. Requires a secure context.lib.batteryChargingTime()
(async function) returns the seconds until the device's battery is fully charged, as aNumber
. Will not work in Safari, Firefox and Webview. Requires a secure context.lib.batteryDischargingTime()
(async function) returns the seconds until the device's battery is fully discharged, as aNumber
. Will not work in Safari, Firefox and Webview. Requires a secure context.
lib.smartGetType(value)
returns the type ofvalue
. It is more advanced than JavaScript'stypeof
operator, as it can recognize arrays, dates, and other types (e.g.,new Error
returns"error"
). This smart type detection function can recognize these JS + Node.js types:- null
- undefined
- NaN
- Infinity
- Symbols
- BigInts
- Functions
- Dates
- DOM objects
- Objects
- Arrays
- Buffers (specific to Node.js only)
- Proxies (outputs as "object")
- Revoked proxy (outputs as "proxy:revoked")
lib.checkPermissions(permission)
returns the state ofpermission
. Check the Mozilla docs for information about the Permissions API.
Step 1: Download lib.js
or the whole repo.
Step 2: Insert <script src="lib.js"></script>
into your project. Remember to tweak the path if necessary.
Step 3: Use the library like so: lib.[the name of the function you want]
. For example, lib.randomNumber(0, 100)
.
Possible outcomes:
console.log(lib.clamp(1000, 0, 100));
would output 100
.
console.log(lib.smartGetType(() => {}))
would output "function"
console.log(lib.randomNumber(20, 100))
could output 45