dhavaltank-js-utils
TypeScript icon, indicating that this package has built-in type declarations

0.0.4 • Public • Published

JavaScript Utility Package (dhavaltank-js-utils)

A collection of functions i use regularly and don't want to write again

Installation

Install my-project with npm

npm install --save dhavaltank-js-utils
yarn add dhavaltank-js-utils

Utils Functions List

  1. capitalizeFirstLetter
  2. titleCase
  3. getInitials
  4. getTruncateDescription
  5. compareArrays
  6. generateOTPWithLength
  7. generateRandomPassword
  8. slugify
  9. setLocalStorage
  10. getLocalStorage
  11. removeLocalStorage
  12. clearLocalStorage
  13. getGreeting
  14. validateText
  15. validateEmail
  16. validatePassword
  17. formatCurrency
  18. removeDuplicatesFromArray
  19. sortArrayByMode
  20. reverseString
  21. isObjectValuesEmpty
  22. checkNotNullAndNotEmpty
  23. handleNaN
  24. isFalsy
  25. isTruthy
  26. groupBy

Documentation

capitalizeFirstLetter(str)

Function Description:

The capitalizeFirstLetter function takes a string as input and returns a new string with the first letter capitalized.

Parameters

  • str (string): The input string to be capitalized.

Return Value

Returns a new string with the first letter capitalized.

import { capitalizeFirstLetter } from "dhavaltank-js-utils";
capitalizeFirstLetter("hello world"); // 'Hello world'

titleCase(str)

Function Description:

The titleCase function takes a string (str) and an optional key (key) as parameters. The purpose of this function is to convert the input string into a title case, where the first letter of each word is capitalized. Additionally, the function allows for a special case where if the key parameter is set to "And," it replaces the occurrence of the word "And" with the ampersand "&" in the final title case string.

Parameters

  • str (string): The input string that needs to be converted to title case.
  • key (string, optional): An optional parameter that, if set to "And," replaces occurrences of "And" with "&" in the final title case string.

Return Value

The function returns the input string converted to title case, with the option to replace "And" with "&" if the key parameter is set accordingly.

import { titleCase } from "dhavaltank-js-utils";
titleCase("hello world"); // 'Hello World'

getInitials(str)

Function Description:

The getInitials function takes a name parameter, which is expected to be a string containing one or more words. The function aims to generate initials based on the first letter of each word in the input string. If the input string is a single word, the function returns the uppercase first and last letters of that word as the initials. If the input string consists of multiple words, the function concatenates the uppercase first letters of each word to form the initials.

Parameters

  • name (string): The input string from which initials are to be generated.

Return Value

The function returns the initials generated from the input string. If the input is not a valid string or is empty, the function returns a question mark ("?").

import { getInitials } from "dhavaltank-js-utils";
getInitials("hello"); // 'H'
getInitials("hello world"); // 'HW'
getInitials("hello world User"); // 'HU'

getTruncateDescription(str)

Function Description:

The getTruncateDescription function takes a text parameter (a string) and an optional maxLength parameter (default value is 10). The purpose of this function is to truncate the input string to a specified maximum length and append an ellipsis ("...") if the original string length exceeds the specified maximum length.

Parameters

  • text (string): The input string that may need truncation.
  • maxLength (number, optional): The maximum length to which the input string should be truncated. Defaults to 10 if not provided.

Return Value

The function returns the truncated string, followed by an ellipsis if the original string length exceeds the specified maximum length. If the input string is empty or falsy, an empty string is returned.

import { getTruncateDescription } from "dhavaltank-js-utils";
getTruncateDescription("Hello World User"); // 'Hello Worl...'

compareArrays(array1, array2)

Function Description:

The compareArrays function takes two arrays (arr1 and arr2) as parameters and checks if they are equal. Equality in this context means that the arrays contain the same elements, regardless of their order.

Parameters

  • arr1 (array): The first array for comparison.
  • arr2 (array): The second array for comparison.

Return Value

The function returns true if the arrays are equal, i.e., they contain the same elements regardless of order. It returns false otherwise.

import { compareArrays } from "dhavaltank-js-utils";
compareArrays([1, 2, 3], [3, 1, 2]); // true
compareArrays([1, 2, 3], [4, 5, 6]); // false

generateOTPWithLength(length)

Function Description:

The generateOTPWithLength function is a utility for generating one-time passwords (OTPs) in JavaScript. It creates numeric or alphanumeric passwords of a specified length.

Parameters

  • length (number): The desired length of the generated OTP.
  • isAlphaNumeric (boolean): (optional, default: false): A boolean flag to determine whether the OTP should include alphanumeric characters.

Return Value

Returns a string representing the generated OTP.

import { generateOTPWithLength } from "dhavaltank-js-utils";
generateOTPWithLength(4); // 7519
generateOTPWithLength(6); // 195742
generateOTPWithLength(8, true); // rT9sLpQ7

generateRandomPassword(length)

Function Description:

The generateRandomPassword function is a JavaScript utility designed to create random passwords. It generates passwords of a specified length with a mix of lowercase and uppercase letters, digits, and special characters.

Parameters

  • length (number): (optional, default: 8): The desired length of the generated password.

Return Value

Returns a string representing the randomly generated password.

import { generateRandomPassword } from "dhavaltank-js-utils";
generateRandomPassword(12); // aB3$XyZi8Lq

slugify(string, separator)

Function Description:

The slugify function takes a string parameter and an optional separator parameter (default is "-"). Its purpose is to generate a URL-friendly slug from the input string. The slug is created by converting the string to lowercase, removing non-word characters, replacing spaces and underscores with the specified separator, and ensuring proper formatting.

Parameters

  • string (string): The input string to be converted into a slug.
  • separator (string, optional): The character used to replace spaces and underscores in the slug. Defaults to "-".

Return Value

The function returns the generated slug based on the input string. If the input string is empty or falsy, an empty string is returned.

import { slugify } from "dhavaltank-js-utils";
slugify('some string') // some-string
slugify('some string',"_") // some_string

setLocalStorage(key, data)

Function Description:

The setLocalStorage function takes a key and data as parameters, aiming to store data in the browser's localStorage. It converts the data to a JSON string before storing it.

Parameters

  • key (string): The key under which the data will be stored in localStorage.
  • data (any): The data to be stored in localStorage.

Return Value

The function returns true if the data is successfully stored in localStorage; otherwise, it logs an error and returns false.

import { setLocalStorage } from "dhavaltank-js-utils";
setLocalStorage("user",{"name":"test user", "id": "123"}); // true

getLocalStorage(key)

Function Description:

The getLocalStorage function takes a key as a parameter and retrieves data from the browser's localStorage. It attempts to parse the stored data as JSON.

Parameters

  • key (string): The key under which the data is stored in localStorage.

Return Value

The function returns the parsed data if it exists, or null if the data doesn't exist or cannot be parsed. It also logs an error if there is an issue retrieving the data.

import { getLocalStorage } from "dhavaltank-js-utils";
getLocalStorage("user"); // {"name":"test user", "id": "123"}

removeLocalStorage(key)

Function Description:

The removeLocalStorage function takes a key as a parameter and removes the corresponding data from localStorage.

Parameters

  • key (string): The key under which the data is stored in localStorage.

Return Value

The function returns true if the data is successfully removed from localStorage; otherwise, it logs an error and returns false.

import { removeLocalStorage } from "dhavaltank-js-utils";
removeLocalStorage("user"); // {"name":"test user", "id": "123"}

clearLocalStorage()

Function Description:

The clearLocalStorage function clears all data stored in the browser's localStorage.

Return Value

The function returns true if the localStorage is successfully cleared; otherwise, it logs an error and returns false.

import { clearLocalStorage } from "dhavaltank-js-utils";
clearLocalStorage("user"); // true

getGreeting()

Function Description:

The getGreeting function returns a greeting message based on the current time of day. It determines the time of day (morning, afternoon, or evening) and returns the corresponding greeting.

Return Value

The function returns a string representing the appropriate greeting for the current time of day.

import { getGreeting } from "dhavaltank-js-utils";
getGreeting(); // Good morning!

validateText(value, errorMessage)

Function Description:

The validateText function takes a value parameter (presumably a text input) and an optional errorMessage parameter. It checks if the input is empty or contains only whitespaces. If the input is invalid, it returns an error object with the specified or default error message.

Parameters

  • value (string): The text input to be validated.
  • errorMessage (string, optional): Custom error message for the validation. Defaults to "This field must not be empty."

Return Value

The function returns an object with isError indicating whether the input is valid or not, and errorMessage providing the error message if isError is true.

import { validateText } from "dhavaltank-js-utils";
validateText('John Doe') // { isError: false, errorMessage: 'Valid input' }

validateEmail(value, errorMessage)

Function Description:

The validateEmail function takes an email parameter and an optional errorMessage parameter. It checks if the email input is empty or if it matches a regular expression for a valid email format.

Parameters

  • email (string): The email input to be validated.
  • errorMessage (string, optional): Custom error message for the validation. Defaults to "This field must not be empty."

Return Value

The function returns an object with isError indicating whether the email is valid or not, and errorMessage providing the error message if isError is true.

import { validateEmail } from "dhavaltank-js-utils";
validateEmail('test@example.com');// { isError: false, errorMessage: 'Valid email' }

validatePassword(value, errorMessage)

Function Description:

The validatePassword function takes a password parameter and an optional errorMessage parameter. It checks if the password input meets certain criteria, such as a minimum length and the inclusion of uppercase letters, lowercase letters, numbers, and symbols.

Parameters

  • password (string): The password input to be validated.
  • errorMessage (string, optional): Custom error message for the validation. Defaults to "This field must not be empty."

Return Value

The function returns an object with isError indicating whether the password is valid or not, and errorMessage providing the error message if isError is true.

import { validatePassword } from "dhavaltank-js-utils";
validatePassword('Abc@1234.com');// { isError: false, errorMessage: 'Valid password' }

validateMobileNumber(value, errorMessage)

Function Description:

The validateMobileNumber function takes a value parameter and an optional errorMessage parameter. It checks if the input is a valid 10-digit mobile number.

Parameters

  • value (string): The mobile number input to be validated.
  • errorMessage (string, optional): Custom error message for the validation. Defaults to "This field must not be empty."

Return Value

The function returns an object with isError indicating whether the mobile number is valid or not, and errorMessage providing the error message if isError is true.

import { validateMobileNumber } from "dhavaltank-js-utils";
validateMobileNumber(12345467890);// { isError: false, errorMessage: 'Valid mobile number' }

formatCurrency(value, CurrencyCode, minimumFractionDigits, maximumFractionDigits)

Function Description:

The formatCurrency function is a JavaScript utility for formatting numbers as currency strings. It uses the toLocaleString method to format a given number with specified currency code and fraction digits.

Parameters

  • value (number): (required): The numeric value to be formatted as currency.
  • currencyCode (optional, default: CurrencyCode.USD): The currency code to use for formatting (e.g., 'USD', 'EUR', 'GBP', etc.).
  • minimumFractionDigits (optional, default: 2): The minimum number of fraction digits to display.
  • maximumFractionDigits (optional, default: 2): The maximum number of fraction digits to display.

Return Value

Returns a string representing the formatted currency.

import { formatCurrency } from "dhavaltank-js-utils";
formatCurrency(12345.67); // $12,345.67
formatCurrency(amount, CurrencyCode.GBP, 1, 3); // £9,876.543

removeDuplicatesFromArray(array)

Function Description:

The removeDuplicatesFromArray function is a JavaScript utility for removing duplicate elements from an array. It utilizes the Set data structure to ensure uniqueness and returns a new array without duplicates.

Parameters

  • array (required): The input array containing elements with potential duplicates.

Return Value

Returns a new array with duplicate elements removed.

import { removeDuplicatesFromArray } from "dhavaltank-js-utils";
removeDuplicatesFromArray([1, 2, 3, 2, 4, 5, 1]); // [1, 2, 3, 4, 5]
removeDuplicatesFromArray(['apple', 'banana', 'orange', 'apple', 'grape', 'banana']); // £9,876.543

sortArrayByMode(array, mode)

Function Description:

The sortArrayByMode function is a JavaScript utility for sorting an array based on a specified mode (ascending or descending). It can also handle sorting objects within the array based on a specified key.

Parameters

  • array (required): The input array to be sorted.
  • mode (optional, default: 'asc'): The sorting mode, either 'asc' for ascending or 'desc' for descending.
  • key (optional, default: null): The key to use for sorting objects within the array. If null, the array elements themselves are sorted.

Return Value

Returns a new array sorted based on the specified mode and key.

import { sortArrayByMode } from "dhavaltank-js-utils";
sortArrayByMode([3, 1, 4, 1, 5, 9, 2, 6]); // [1, 1, 2, 3, 4, 5, 6, 9]
sortArrayByMode([3, 1, 4, 1, 5, 9, 2, 6], 'desc'); // [9, 6, 5, 4, 3, 2, 1, 1]

reverseString(str)

Function Description:

The reverseString function is a JavaScript utility for reversing a given string. It uses the split, reverse, and join methods to efficiently reverse the characters in the string.

Parameters

  • str (required): The input string to be reversed.

Return Value

Returns a new string with the characters reversed.

import { reverseString } from "dhavaltank-js-utils";
reverseString('Hello, World!'); // '!dlroW ,olleH'

isObjectValuesEmpty(obj)

Function Description:

The isObjectValuesEmpty function is a JavaScript utility for checking if any values in an object are empty or falsy. It uses the reduce method to iterate through the object's keys and builds an errors object containing keys with empty values.

Parameters

  • object (required): The input object to check for empty values.

Return Value

Returns true if any values in the object are empty or falsy, otherwise returns false.

import { isObjectValuesEmpty } from "dhavaltank-js-utils";
const exampleObject = {
  name: 'John Doe',
  age: 30,
  email: '',
  address: null,
};
isObjectValuesEmpty(exampleObject); // true

checkNotNullAndNotEmpty(value)

Function Description:

The checkNotNullAndNotEmpty function is a JavaScript utility for checking if a value is not undefined, not null, and not an empty string. It also considers falsy values like 0 as valid.

Parameters

  • value (required): The input value to check for not being undefined, not null, and not an empty string.

Return Value

Returns true if the value is not undefined, not null, and not an empty string; otherwise, returns false.

import { checkNotNullAndNotEmpty } from "dhavaltank-js-utils";
checkNotNullAndNotEmpty("Hello, World!"); // true
checkNotNullAndNotEmpty("); // false

handleNaN(value)

Function Description:

The handleNaN function is a JavaScript utility for handling NaN (Not-a-Number) values. It checks if a value is NaN and returns either the original value or a specified fallback value.

Parameters

  • value (required): The input value to check for being NaN.
  • returnValue (optional, default: 0): The fallback value to return if the input value is NaN.

Return Value

Returns the original value if it is not NaN; otherwise, returns the specified fallback value.

import { handleNaN } from "dhavaltank-js-utils";
handleNaN(42); // 42
handleNaN("Not a Number"); // 0
handleNaN("Not a Number", null); // null

isFalsy(value)

Function Description:

The isFalsy function is a JavaScript utility that checks whether a given value is falsy.

Parameters

  • value (required): The input value to check for falsiness.

Return Value

Returns true if the input value is falsy; otherwise, returns false.

import { isFalsy } from "dhavaltank-js-utils";
isFalsy(null); // true
isFalsy(""); // true
isFalsy(42); // false

isTruthy(value)

Function Description:

The isTruthy function is a JavaScript utility that checks whether a given value is truthy.

Parameters

  • value (required): The input value to check for truthiness.

Return Value

Returns true if the input value is truthy; otherwise, returns false.

import { isTruthy } from "dhavaltank-js-utils";
isTruthy(null); // true
isTruthy(""); // false
isTruthy(0); // false

groupBy(value)

Function Description:

The groupBy function is a JavaScript utility for grouping an array of objects by a specified key.

Parameters

  • arr (required): The input array of objects to be grouped.
  • key (required): The key by which the objects in the array should be grouped.

Return Value

Returns an object where keys are unique values of the specified key, and values are arrays of objects grouped by that key.

import { groupBy } from "dhavaltank-js-utils";
const exampleData = [
  { id: 1, category: 'A', value: 42 },
  { id: 2, category: 'B', value: 65 },
  { id: 3, category: 'A', value: 78 },
];
groupBy(exampleData, 'category'); // { A: [{ id: 1, category: 'A', value: 42 }, { id: 3, category: 'A', value: 78 }], B: [{ id: 2, category: 'B', value: 65 }] }

Authors

Hi, I'm Dhaval Tank! 👋

🚀 About Me

👩‍💻 I'm a MERN stack developer.

portfolio linkedin

License

MIT

Contributing

Contributions are always welcome! Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. Please make sure to update tests as appropriate.

Package Sidebar

Install

npm i dhavaltank-js-utils

Weekly Downloads

8

Version

0.0.4

License

MIT

Unpacked Size

60.9 kB

Total Files

6

Last publish

Collaborators

  • dhavaltank