0.8.0 • Published 12 months ago

@sveltinio/ts-utils v0.8.0

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

A bunch of common utilities in pure Typescript to deal with primitives, strings, urls, objects, collections, dates etc.

The package has been created to make my life easier with the requirements of Sveltin based projects and its packages. Anyhow, Sveltin is definitely not mandatory and you could find something fitting your needs.

Installation

npm install @sveltinio/ts-utils
# or
pnpm add @sveltinio/ts-utils
# or
yarn add @sveltinio/ts-utils

Usage

The package supports ES Module and Common JS formats.

ESM

import { isString, isRegExp } from '@sveltinio/ts-utils/is';
import { contains, uniq } from '@sveltinio/ts-utils/collections';
import { isEmpty, camelToKebab } from '@sveltinio/ts-utils';
// ...

CJS

const { hasProperty, hasPropertyValue } = require('@sveltinio/ts-utils/objects')

Type-Safe Error Handling

Except the functions returning a boolean value, the others mainly return a Result type that represents either success (Ok) or failure (Err) from neverthrow for a type-safe error handling.

// from neverthrow docs
type Result<T, E>
  = Ok<T, E>  // contains a success value of type T
  | Err<T, E> // contains a failure value of type E

The ways to access the return value from a Result type may vary based on the use-case and your programming style. Below some samples for quick reference:

import { toKebabCase } from '@sveltinio/ts-utils/strings';

toKebabCase('hello world').value;
// => "hello-world"

const result1 = toKebabCase('hello world');
if (result1.isOk()) {
  console.log(result1.value); // => "hello-world"
}

const result2 = toKebabCase('hello world').match(
  (str) => str, // => "hello-world"
  (err) => `${err.message}`
);
console.log(result2);

toKebabCase(2)
  .map((str) => console.log(str))
  .mapErr((err) => {
    throw new Error(err.message); // => Error: [strings.toKebabCase] Expected string value as input
  });

Refer to the neverthrow documentation for the full picture.

What's inside?

Is

Type guard utilities helping with primitive values and basic objects. Read the docs.

import { ... } from '@sveltinio/ts-utils/is';
NameDescription
isBoolChecks if a given value is of type boolean
isNumberChecks if a given value is of type number
isBigIntChecks if a given value is of type bigint
isStringChecks if a given value is of type string
isArrayChecks if a given value is an array
isObjectChecks if a given value is an object
isPlainObjectChecks if a given value is a plain JavaScript object
isFunctionChecks if a given value is of type function
isSymbolChecks if a given value is of type symbol
isDateChecks if a given value is a valid Date object
isRegExpChecks if a given value is a valid RegExp object
isDefinedChecks if a given value is defined and not null
isTruthyChecks if a given value is a truthy value
isNullishChecks if a value is null or undefined
isNullChecks if a given value is null
isUndefinedChecks if a given value is undefined
isEmptyChecks if a given value is empty or not

Collections

Some utilities to deal with arrays. Read the docs.

import { ... } from '@sveltinio/ts-utils/collections';
NameDescription
sortBySorts an array of objects based on a specified property and order
groupedByOne(1:1) Groups an array of objects by a specified property and returns an array of grouped objects
groupedByMany(1:many) Groups an array of objects by a specified property and returns an array of grouped objects
pickRandomPicks random values from an array of numbers or strings
shuffleShuffles the elements of an array of number, or string values randomly
shuffleByPropertyShuffles an array of plain JavaScript objects by the specified property
containsChecks if an array contains a given value or an array of values
uniqRemoves duplicates from an array of numbers or strings

Colors

Some utilities to deal with hex color strings. Read the docs.

import { ... } from '@sveltinio/ts-utils/colors';
NameDescription
isHexChecks if a given string is a valid hexadecimal color code
getHexValueReturns either the substring after the first character (if the string is a valid hex value) or an error message
randomHexColorReturns a string representing a random hex color

Dates

Some utilities to deal with javascript Dateobjects. Read the docs.

import { ... } from '@sveltinio/ts-utils/dates';
NameDescription
padTo2DigitsGiven a number, returns a string that is the number padded to two digits
dayOfMonthGiven a date string in the format MM/DD/YYYY, returns the day of the month
formatDateGiven a date object, returns a string in the format DD/MM/YYYY
formatDateISOGiven a date object, returns a string in the format YYYY-MM-DD
monthShortGiven a date string in the format MM/DD/YYYY, returns the short month name

Objects

Some utilities to deal with javascript objects, their properties and values. Read the docs.

import { ... } from '@sveltinio/ts-utils/objects';
NameDescription
hasPropertyChecks if a plain JavaScript object has a specified property
hasPropertiesChecks if an object has all the specified properties
hasPropertyValueChecks if an object has the specified property with the given value and same type
hasPropertiesWithValueChecks if an object has the specified properties with the given values
mergeRecursively merges two objects of compatible types
getPropertyValueGets the value of a property on an object
mapToCssVarsReturns a CSS variable string from a plain object with key-value pairs

Paths

Some utilities to deal with path strings. Read the docs.

The functions do not interface with the real file system but they are used to extract some information from the given path string. It means not ensuring e.g. a file exists or a folder is a real folder on the disk. For that, simply use what already exists.

Some look useless at first glance but they are not for Sveltin project requirements.

import { ... } from '@sveltinio/ts-utils/paths';
NameDescription
isDirChecks if a given path is a directory
isFileChecks if a given path is a file path
dirnameReturns the directory name from a given file path
filenameReturns the filename from a given file path
isImageChecks if a given string is a valid image file name (jpg, jpeg, png, gif, webp, or avif)
lastSegmentReturns the last segment of a given path string

Strings

Some utilities to deal with strings and string conversions. Read the docs.

import { ... } from '@sveltinio/ts-utils/strings';
NameDescription
normalizeNormalizes a string by replacing non-word characters with a space character
capitalizeCapitalizes first letter of the string and lowercase the rest
capitalizeAllCapitalizes first letters of each word in a string
uppercaseConverts a string to uppercase
lowercaseConverts a string to lowercase
removeTrailingSlashRemoves all trailing slashes from a string
textBetweenReturns the substring between start and end delimiters
toSlugRemoves all non-word characters, and replaces all spaces with dashes
toTitleReplaces all dashes with spaces, and capitalizes all words
toSnakeCaseConverts a string to snake_case format
toKebabCaseConverts a string to kebab-case format
toCamelCaseConverts a string to camelCase format
toPascalCaseConverts a string to PascalCase format
camelToSnakeConverts a camelCase string to snamecase format
camelToKebabConverts a camelCase string to kebab-case format
isCommaSeparatedChecks if a given string contains a comma-separated list
toCommaSeparatedReplaces all whitespace and semicolons with commas to return a comma-separated string
removeFirstOccurenceRemoves the first occurrence of a specified string from a given text.

Urls

Some utilities to deal with urls. Read the docs.

Some look useless at first glance but they are not for Sveltin project requirements.

import { ... } from '@sveltinio/ts-utils/urls';
NameDescription
isUrlChecks if a given string is a valid URL
canonicalUrlGiven a base URL and a pathname, returns a canonical URL
makeImagePathMakes the full qualified path to the image file
parentUrlGiven an URL, returns the parent url of it (w/o the last segment of the pathname)
parentPathnameGiven an URL, returns the parent pathname (w/o the last segment of the it)
pathSegmentsExtracts the path segments from a valid URL and returns them as an array

License

Free and open-source software under the MIT License