This is a zero-dependency collection of utility tools that will help development on vanilla-js a bit easier for you. I have always appreciated the no-framework idea for most small projects which do not require a lot of maintenance. And these are the sets of tools that I have always had in my projects in some way or form. I have compiled them here with improvements such that they are helpful in a more macroscopic level. I will keep updating it with more tools.
Access it by using this library. Or you can use it in your frontend code like this
<script src="https://mirror.harshankur.com/vanillaUtils.min.js" crossorigin="anonymous"><script>Below is the documentation for this project.
- createElement(tagName, [attributes]) ⇒
HTMLElement Creates an element with a given attribute map in the argument for a given tagName.
- openLink(url, [newTab]) ⇒
void Opens the link provided in the argument 'url'. Based on the other argument 'newTab', it either opens it in the same tab or in a new tab. NOTE: In the case of trying to open this url in a new tab, the browser might first ask the user to enable popups for this website instead of directly opening the link.
- downloadLink(url) ⇒
void Downloads the content of the url passed in the argument. NOTE: You can only trigger download of a url which is in the same domain as the current one. There is Cross-Site access for downloads. If you pass a url from another domain, the browser usually just opens the file on the same tab which might result in loss of unsaved data in the current page.
- guessMimeType(bytes) ⇒
string Guess the MIME type based on the initial bytes of a file.
- downloadFileFromBytes(bytes, name, [type]) ⇒
void Saves the content of the byteArray passed in the argument with its filename passed in the argument.
- fetchRequest(url, [config]) ⇒
Promise.<any> Fetch handler for a request with body.
- setCookie(key, value, [config]) ⇒
void Sets cookie on the browser for the given key and value for the given duration
- getCookie(key) ⇒
string Fetches cookie value for a given key.
- removeCookie(key) ⇒
void Remove cookie for a given key.
- toPromise(fn, args) ⇒
Promise.<any> This takes a function and returns a promisied version of it. Basically it resolves after this fn is executed. It is helpful primarily when one is switching over multiple cases and some of them do not return a promise but it is easier to handle all the cases in promises.
- debounce(fn, t) ⇒
function Debounces a function, i.e., ignored repeated calls for a function. It rather takes the last call while it is waiting.
- capitalize(str) ⇒
string Capitalizes the first letter of a string.
- truncate(str, length) ⇒
string Truncates a string to a specified length and adds an ellipsis (...) if it exceeds that length.
- slugify(str) ⇒
string Converts a string into a URL-friendly slug. Converts to lowercase, removes non-word characters, and replaces spaces with dashes.
- clamp(num, min, max) ⇒
number Clamps a number between a minimum and maximum value.
- formatCurrency(amount, [currency], [locale]) ⇒
string Formats a number as a currency string.
- isValidEmail(email) ⇒
boolean Checks if a string is a valid email address. Uses a simple regex for basic validation.
- isValidUrl(url) ⇒
boolean Checks if a string is a valid URL.
- sum(arr) ⇒
number Calculates the sum of an array of numbers.
- max(arr) ⇒
number Finds the maximum number in an array.
- min(arr) ⇒
number Finds the minimum number in an array.
- groupBy(arr, fn) ⇒
object Groups items of an array based on a key returned by a callback function.
- FetchConfig :
Object - CookieConfig :
Object
Creates an element with a given attribute map in the argument for a given tagName.
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| tagName | string |
A tag name for this new element to be created. | |
| [attributes] | Object.<string, any> |
{} |
We will use this object's keys as attributes for the element and its values as the attribute values. |
Example
const attributes = {
class: 'class1 class2',
id: 'id1',
style: '{ display: "flex"; }',
'data-region': 'Germany'
};
const element = createElement('div', attributes);
// <div class="class1 class2" id="id1" style="{ display: "flex"; }" data-region="Germany"></div>Example
const attributes = {
href: 'https://blog.harshankur.com',
target: '_blank'
};
const element = createElement('a', attributes);
// <a href="https://blog.harshankur.com" target="_blank"></a>Opens the link provided in the argument 'url'. Based on the other argument 'newTab', it either opens it in the same tab or in a new tab. NOTE: In the case of trying to open this url in a new tab, the browser might first ask the user to enable popups for this website instead of directly opening the link.
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| url | string |
The url that you want to open on the client's browser. | |
| [newTab] | boolean |
false |
Flag whether to open this url in a new tab. Please note that passing this true might get the new link (popup) blocked depending on the browser settings. |
Example
openLink("https://github.com/harshankur", true);Downloads the content of the url passed in the argument. NOTE: You can only trigger download of a url which is in the same domain as the current one. There is Cross-Site access for downloads. If you pass a url from another domain, the browser usually just opens the file on the same tab which might result in loss of unsaved data in the current page.
Kind: global function
| Param | Type | Description |
|---|---|---|
| url | string |
The url from which you wish to trigger a content download. |
Example
downloadLink("https://mirror.harshankur.com/vanillaUtils.min.js");Guess the MIME type based on the initial bytes of a file.
Kind: global function
Returns: string - The guessed MIME type or 'application/octet-stream' if unknown.
| Param | Type | Description |
|---|---|---|
| bytes | Uint8Array |
The byte array representing the file content. |
- guessMimeType(bytes) ⇒
string- ~signatures :
Object.<string, string> - ~getHexString(byteArray) ⇒
string
- ~signatures :
Known file signatures mapped to their corresponding MIME types.
Kind: inner constant of guessMimeType
Converts a byte array to a hexadecimal string.
Kind: inner method of guessMimeType
Returns: string - The hexadecimal string representation of the byte array.
| Param | Type | Description |
|---|---|---|
| byteArray | Uint8Array |
The byte array to convert. |
Saves the content of the byteArray passed in the argument with its filename passed in the argument.
Kind: global function
| Param | Type | Description |
|---|---|---|
| bytes | Uint8Array |
File bytes. |
| name | string |
The name of the file in the download |
| [type] | string |
File Mimetype |
Example
downloadFileFromBytes(<bytes>, 'myFile.pdf');Fetch handler for a request with body.
Kind: global function
Returns: Promise.<any> - Returns a Promise for the fetch request.
| Param | Type | Default | Description |
|---|---|---|---|
| url | string |
Url to make this fetch request. | |
| [config] | FetchConfig |
{} |
Config for this fetch request. |
Example
fetchRequest('https://mirror.harshankur.com/vanillaUtils.min.js')
// GET https://mirror.harshankur.com/vanillaUtils.min.jsExample
const params = {
method: 'POST',
header: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ name: "Harsh Ankur" })
};
fetchRequest('https://post-example.com/registerName', params);
// POST https://post-example.com/registerName -H "Content-Type: application/json" -d '{ "name": "Harsh Ankur" }'Sets cookie on the browser for the given key and value for the given duration
Kind: global function
| Param | Type | Default | Description |
|---|---|---|---|
| key | string |
Key of the cookie | |
| value | string |
Value to be set for this cookie | |
| [config] | CookieConfig |
{} |
[OPTIONAL] Configuration for settings cookies |
Example
setCookie("key1", "value1");
// Setting session specific cookie for key1: value1Example
setCookie("key2", "value2", { expires: 30, path: '/' });
// Setting key2: value2 cookie on the root domain that expires in 30 days.Fetches cookie value for a given key.
Kind: global function
Returns: string - Value of the cookie for the corresponding key.
| Param | Type | Description |
|---|---|---|
| key | string |
Key of the cookie. |
Example
const storedValue = getCookie("key1");
// "value1"Example
const storedValue = getCookie("key2");
// "value2"Remove cookie for a given key.
Kind: global function
| Param | Type | Description |
|---|---|---|
| key | string |
Key of the cookie |
Example
getCookie("key1");
// "value1"
removeCookie("key1");
getCookie("key1");
// ""This takes a function and returns a promisied version of it. Basically it resolves after this fn is executed. It is helpful primarily when one is switching over multiple cases and some of them do not return a promise but it is easier to handle all the cases in promises.
Kind: global function
Returns: Promise.<any> - Promise that will be resolved once the fn function is executed.
| Param | Type | Description |
|---|---|---|
| fn | function |
Function that is needed to be promisied. |
| args | Array.<any> |
Array of arguments to be called for this function. |
Debounces a function, i.e., ignored repeated calls for a function. It rather takes the last call while it is waiting.
Kind: global function
| Param | Type | Description |
|---|---|---|
| fn | function |
Function needed to debounce |
| t | number |
milliseconds delay for debouncing. |
Capitalizes the first letter of a string.
Kind: global function
Returns: string - The string with its first character converted to uppercase.
| Param | Type | Description |
|---|---|---|
| str | string |
The string to capitalize. |
Example
capitalize("hello world")
// "Hello world"Truncates a string to a specified length and adds an ellipsis (...) if it exceeds that length.
Kind: global function
Returns: string - The truncated string with '...' appended if truncated.
| Param | Type | Description |
|---|---|---|
| str | string |
The string to truncate. |
| length | number |
The maximum length of the string before truncation. |
Example
truncate("Hello World", 5)
// "Hello..."Converts a string into a URL-friendly slug. Converts to lowercase, removes non-word characters, and replaces spaces with dashes.
Kind: global function
Returns: string - The clean, slugified string.
| Param | Type | Description |
|---|---|---|
| str | string |
The string to slugify. |
Example
slugify("Hello World!")
// "hello-world"Clamps a number between a minimum and maximum value.
Kind: global function
Returns: number - The clamped value.
| Param | Type | Description |
|---|---|---|
| num | number |
The number to clamp. |
| min | number |
The minimum allowed value. |
| max | number |
The maximum allowed value. |
Example
clamp(100, 0, 50)
// 50Formats a number as a currency string.
Kind: global function
Returns: string - The formatted currency string.
| Param | Type | Default | Description |
|---|---|---|---|
| amount | number |
The number to format. | |
| [currency] | string |
"'USD'" |
The currency code (e.g., 'USD', 'EUR'). |
| [locale] | string |
"'en-US'" |
The locale string (e.g., 'en-US', 'de-DE'). |
Example
formatCurrency(1234.56)
// "$1,234.56"Checks if a string is a valid email address. Uses a simple regex for basic validation.
Kind: global function
Returns: boolean - True if valid, false otherwise.
| Param | Type | Description |
|---|---|---|
string |
The email string to check. |
Example
isValidEmail("test@example.com")
// trueChecks if a string is a valid URL.
Kind: global function
Returns: boolean - True if valid, false otherwise.
| Param | Type | Description |
|---|---|---|
| url | string |
The URL string to check. |
Example
isValidUrl("https://google.com")
// trueCalculates the sum of an array of numbers.
Kind: global function
Returns: number - The total sum.
| Param | Type | Description |
|---|---|---|
| arr | Array.<number> |
The array of numbers to sum. |
Example
sum([1, 2, 3])
// 6Finds the maximum number in an array.
Kind: global function
Returns: number - The maximum value.
| Param | Type | Description |
|---|---|---|
| arr | Array.<number> |
The array to search. |
Example
max([1, 5, 2])
// 5Finds the minimum number in an array.
Kind: global function
Returns: number - The minimum value.
| Param | Type | Description |
|---|---|---|
| arr | Array.<number> |
The array to search. |
Example
min([1, 5, 2])
// 1Groups items of an array based on a key returned by a callback function.
Kind: global function
Returns: object - An object where keys are the groups and values are arrays of items.
| Param | Type | Description |
|---|---|---|
| arr | Array |
The array to group. |
| fn | function |
The callback function that returns the key to group by. |
Example
groupBy([1.1, 1.2, 2.1], Math.floor)
// { '1': [1.1, 1.2], '2': [2.1] }Kind: global typedef
Properties
| Name | Type | Description |
|---|---|---|
| [method] | 'DELETE' | 'GET' | 'POST' | 'PUT' |
Method of the fetch call. Default is 'GET'. |
| [mode] | 'no-cors' | 'cors' | 'navigate' | 'websocket' | 'same-origin' |
Cross-Origin Mode. Default is 'cors' if the fetch is created using Request constructor. Otherwise it is 'no-cors'. |
| [cache] | 'default' | 'no-cache' | 'reload' | 'force-cache' | 'only-if-cached' |
Cache Policy. Default is 'default'. |
| [credentials] | 'include' | 'same-origin' | 'omit' |
Credentials Policy. Default is 'same-origin'. |
| [redirect] | 'manual' | 'follow' | 'error' |
Redirect Policy. Default is 'follow'. |
| [referrerPolicy] | 'no-referrer' | 'no-referrer-when-downgrade' | 'origin' | 'origin-when-cross-origin' | 'same-origin' | 'strict-origin' | 'strict-origin-when-cross-origin' | 'unsafe-url' |
Refferer Policy. Default is 'no-referrer-when-downgrade'. |
| [headers] | object |
Header for this fetch request. Default is an empty object. |
| [body] | object | string |
Body for this fetch request. Body data type must match "Content-Type" header. |
Kind: global typedef
Properties
| Name | Type | Description |
|---|---|---|
| [expires] | number |
Number of DAYS after which this cookie will be expired. If not specified, it would mean that the cookie is session-specific. |
| [path] | string |
Indicates the path that must exist in the requested URL for the browser to send the Cookie header (e.g., '/', '/mydir'). If not specified, it defaults to the current path of the current document location. |
| [samesite] | string |
Prevents the browser from sending this cookie along with cross-site requests. Possible values are lax, strict or none. Strict prevents from sending to cross-site requests. Lax allows a few basic cross-site requests but prevents many Cross-Site Requesst Forgery attacks. Default is None which implies no restriction. |
| [secure] | boolean |
Specifies that the cookie should only be transmitted over a secure protocol. Default is true which would mean that this cookie will be sent over only in secure communications. |