0.0.2 • Published 8 months ago

littlejshelper v0.0.2

Weekly downloads
-
License
ISC
Repository
-
Last release
8 months ago

Utility Functions

This repository contains various utility functions for handling common tasks in JavaScript.

⚠️ Warning: This package is intended for my personal & internal use. Its release cycle does not follow SemVer, which means I might release breaking changes (change APIs, remove functionality) without any prior warning.

If you are using this package, it would be helpful if you could help me gain an understanding where, how and why you are using it.

Table of Contents

  1. Installing Guidelines
  2. Browser Support
  3. Functions

Installing Guidelines

To get started with using the utility functions, follow these steps:

  1. Install the package:

    npm install littlejshelper
  2. Import the package: You can import individual utility functions as needed in your JavaScript code:

import { generateRandomString, isDarkMode } from "littlejshelper";
  1. Usage: Example of using the generateRandomString function:
const randomString = generateRandomString(10);
console.log(randomString);

Browser Support

These utility functions are designed to work across modern browsers. We support the following:

  • Chrome (latest version)
  • Firefox (latest version)
  • Safari (latest version)
  • Edge (latest version)

Compatibility Notes: Some functions (like window.matchMedia used in isDarkMode) may not be supported in older browsers like Internet Explorer. If you require support for older browsers, consider using a polyfill for certain functions or adapting your code.

Functions

getFormattedDate

const formattedDate = getFormattedDate(
  new Date(),
  "en-GB",
  { weekday: "long", year: "numeric", month: "long", day: "numeric" },
  true
);
console.log(formattedDate);
// Output: "Tuesday, 18 December 2024, 10:30 AM"

Parameters:

  • date: The date to format (string or Date object).
  • locale (optional): The locale to use for formatting the date (default is "en-US").
  • options (optional): The custom date format options.
  • includeTime (optional): Whether to include time in the formatted date string (default is false).

Returns:
Formatted date string, including optional time information.


getCurrentYear

const currentYear = getCurrentYear();
console.log(currentYear);
// Output: 2024

Returns:
Current year as a number.


getCurrentMonth

const currentMonth = getCurrentMonth();
console.log(currentMonth);
// Output: 12

Returns:
Current month as a number.


timeAgo

const ago = timeAgo(new Date("2024-12-17"));
console.log(ago);
// Output: "1 day ago"

Parameters:

  • date: The date to compare with the current date (string or Date object).

Returns:
Time ago string (e.g., "5 minutes ago", "2 hours ago").


getDateDifference

const daysDifference = getDateDifference(
  new Date("2024-12-01"),
  new Date("2024-12-18")
);
console.log(daysDifference);
// Output: 17

Parameters:

  • startDate: The start date (string or Date).
  • endDate: The end date (string or Date).

Returns:
The difference in days.


slugify

const slug = slugify("This is a sample text!");
console.log(slug);
// Output: "this-is-a-sample-text"

Parameters:

  • text: The text to convert into a slug.

Returns:
Slugified string.


isValidEmail

const isValid = isValidEmail("test@example.com");
console.log(isValid);
// Output: true

Parameters:

  • email: The email address to validate.

Returns:
Whether the email is valid or not (true or false).


truncateText

const truncated = truncateText(
  "This is a very long text that needs to be shortened.",
  20
);
console.log(truncated);
// Output: "This is a very long..."

Parameters:

  • text: The text to truncate.
  • length (optional): The maximum length (default: 100).

Returns:
The truncated string.


isInViewport

const element = document.querySelector("#someElement");
const isInView = isInViewport(element);
console.log(isInView);
// Output: true or false based on whether the element is in the viewport

Parameters:

  • element: The DOM element to check.

Returns:
Whether the element is in the viewport (true or false).


isValidUrl

const isValid = isValidUrl("https://example.com");
console.log(isValid);
// Output: true

Parameters:

  • url: The URL to validate.

Returns:
Whether the URL is valid or not (true or false).


setLocalStorage

setLocalStorage("user", { name: "John", age: 30 });

Parameters:

  • key: The key for the local storage item.
  • value: The value to store (any serializable value).

getLocalStorage

const user = getLocalStorage("user");
console.log(user);
// Output: { name: 'John', age: 30 }

Parameters:

  • key: The key of the item to retrieve.

Returns:
The parsed value stored under the key, or null if not found.


Utility Functions

This repository contains various utility functions for handling common tasks in JavaScript.

Functions

generateRandomString

const randomString = generateRandomString(10);
console.log(randomString);
// Output: Random string like "a7g6h3r2t1"

Parameters:

  • length (optional): The length of the random string (default is 8).

Returns:
A randomly generated string of the specified length.


isDarkMode

const darkMode = isDarkMode();
console.log(darkMode);
// Output: true or false based on the system's color scheme preference

Returns:
Whether the system is in dark mode (true or false).


removeArrayDuplicates

const uniqueArray = removeArrayDuplicates([1, 2, 2, 3, 4, 4]);
console.log(uniqueArray);
// Output: [1, 2, 3, 4]

Parameters:

  • array: The array to remove duplicates from.

Returns:
A new array with duplicates removed.


getUniqueValuesFromArray

const uniqueNames = getUniqueValuesFromArray(users, "name");
console.log(uniqueNames);
// Output: ["Alice", "Bob"]

Parameters:

  • array: The array to process.
  • key: The key to extract unique values by.

Returns:
A new array with unique values based on the specified key.


minArray

const minValue = minArray([5, 1, 8, 3]);
console.log(minValue);
// Output: 1

Parameters:

  • array: The array to find the minimum value from.

Returns:
The minimum value in the array.


maxArray

const maxValue = maxArray([5, 1, 8, 3]);
console.log(maxValue);
// Output: 8

Parameters:

  • array: The array to find the maximum value from.

Returns:
The maximum value in the array.


sortArrayAsc

const sortedAsc = sortArrayAsc([5, 1, 8, 3]);
console.log(sortedAsc);
// Output: [1, 3, 5, 8]

Parameters:

  • array: The array to sort.

Returns:
A new array sorted in ascending order.


sortArrayDesc

const sortedDesc = sortArrayDesc([5, 1, 8, 3]);
console.log(sortedDesc);
// Output: [8, 5, 3, 1]

Parameters:

  • array: The array to sort.

Returns:
A new array sorted in descending order.


sortArrayByMultipleKeys

const sortedItems = sortArrayByMultipleKeys(items, ["price", "rating"]);
console.log(sortedItems);
// Output: [
//   { name: "Item A", price: 10, rating: 5 },
//   { name: "Item C", price: 10, rating: 4 },
//   { name: "Item B", price: 20, rating: 4 },
// ]

Parameters:

  • array: The array to sort.
  • keys: An array of keys to sort by.

Returns:
A new array sorted by the specified keys.


mergeArraysAndRemoveDuplicates

const mergedArray = mergeArraysAndRemoveDuplicates([1, 2, 3], [3, 4, 5]);
console.log(mergedArray);
// Output: [1, 2, 3, 4, 5]

Parameters:

  • arrays: The arrays to merge.

Returns:
A new array with the merged values and no duplicates.


mergeArrays

const merged = mergeArrays([[1, 2], [3, 4], [5]]);
console.log(merged);
// Output: [1, 2, 3, 4, 5]

Parameters:

  • arrays: The arrays to merge.

Returns:
A new array with all values merged.


objectValuesToArray

const values = objectValuesToArray({ name: "Alice", age: 30 });
console.log(values);
// Output: ["Alice", 30]

Parameters:

  • object: The object to process.

Returns:
An array of the object's values.


objectKeysToArray

const keys = objectKeysToArray({ name: "Alice", age: 30 });
console.log(keys);
// Output: ["name", "age"]

Parameters:

  • object: The object to process.

Returns:
An array of the object's keys.


intersectArrays

const intersection = intersectArrays([1, 2, 3], [2, 3, 4], [3, 4, 5]);
console.log(intersection);
// Output: [3]

Parameters:

  • arrays: The arrays to intersect.

Returns:
A new array with values that are in all input arrays.


filterArrayByValue

const filtered = filterArrayByValue(users2, "age", 30);
console.log(filtered);
// Output: [{ name: "Alice", age: 30 }, { name: "Charlie", age: 30 }]

Parameters:

  • array: The array to filter.
  • key: The key to match.
  • value: The value to match.

Returns:
A new array with objects that match the key-value pair.


filterObjectByValue

const filteredObj = filterObjectByValue({ a: 1, b: 2, c: 1 }, 1);
console.log(filteredObj);
// Output: { a: 1, c: 1 }

Parameters:

  • object: The object to filter.
  • value: The value to filter by.

Returns:
A new object with keys that match the specified value.


mostFrequentElement

const frequentElement = mostFrequentElement([1, 2, 2, 3, 3, 3]);
console.log(frequentElement);
// Output: "3"

Parameters:

  • array: The array to process.

Returns:
The most frequent element in the array.

0.0.2

8 months ago

0.0.1

8 months ago