1.12.0 • Published 10 months ago

@alessiofrittoli/web-utils v1.12.0

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

Web Utils 🛠️

NPM Latest Version Coverage Status Socket Status NPM Monthly Downloads Dependencies

GitHub Sponsor

Common TypeScript web utilities

Table of Contents


Getting started

Run the following command to start using web-utils in your projects:

npm i @alessiofrittoli/web-utils

or using pnpm

pnpm i @alessiofrittoli/web-utils

API Reference

Array utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/arrays'

arrayUnique

Removes duplicate values from an array.

ParameterTypeDescription
arrayT[]The input array.

Type: T[]

The filtered array.


Removes duplicates from array
const pointer = {}
console.log( arrayUnique( [ pointer, 'b', pointer, 'c', 'b' ] ) )
// Outputs: [ {}, 'b', 'c' ]

arrayObjectUnique

Removes duplicate entries from an array referencing an object key.

ParameterTypeDescription
arrayT[]An array of objects.
propertykeyof TThe Object property to refer to.

Type: T[]

The filtered array.


Removes duplicates from array with the same propery value
const arr = [
  { id: 1, name: 'a' },
  { id: 2, name: 'b' },
  { id: 1, name: 'c' }, // duplicate `id`
  { id: 3, name: 'd' },
  { id: 4, name: 'a' }, // duplicate `name`
]

console.log( arrayObjectUnique( arr, 'id' ) )
// Outputs: [
//     { id: 1, name: 'a' },
//     { id: 2, name: 'b' },
//     { id: 3, name: 'd' },
//     { id: 4, name: 'a' },
// ]


console.log( arrayObjectUnique( arr, 'name' ) )
// Outputs: [
//     { id: 1, name: 'a' },
//     { id: 2, name: 'b' },
//     { id: 1, name: 'c' },
//     { id: 3, name: 'd' },
// ]

listToArray

Convert a stringified Array to Array object.

ParameterTypeDescription
stringstringAn array of objects.

Type: string[]

The converted stringified Array to Array object.


Basic usage
console.log( listToArray( '1,2, 3, 4' ).map( Number ) )
// Outputs: [ 1, 2, 3, 4 ]

chunkInto

Split Array into chunks.

ParameterDefaultDescription
Tunknown[]The input array type.

ParameterTypeDescription
arrayT[]The original Array.
optionsChunkIntoOptionsAn object defining split criteria.
options.sizenumberWill split the given Array in a way to ensure each chunk length is, whenever possible, equal to the given value.
options.countnumberWill split the given Array in a way to ensure n chunks as the given value.

Type: T[]

An Array of chunks.


Basic usage
console.log( chunkInto( [ 1, 2, 3, 4, 5 ], { count: 2 } ) )
// Output: [ [ 1, 2, 3 ], [ 4, 5 ] ]

console.log( chunkInto( [ 1, 2, 3, 4, 5 ], { size: 2 } ) )
// Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ]

Blob utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/blob'

downloadBlob

Create and download a blob object.

ParameterTypeDescription
filenamestringThe download file name.
dataBodyInitThe download file data.
initResponseInit(Optional) The ResponseInit object.

Download file from HTTP Response
fetch( ... )
  .then( response => response.formData() )
  .then( async data => {
    await Promise.all(
      Array.from( data.entries() )
        .map( async ( [, file ] ) => {
          if ( ! ( file instanceof File ) ) return
          await downloadBlob( file.name, file )
        } )
    )
  } )
  .catch( error => {
    console.error( error )
  } )

Dom utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/dom'

blockScroll

Prevent Element Overflow.

It calculates the scrollbar width and the resulting value is applied to the target element right padding-right to prevent width grows.

It also applies the --scrollbar-size CSS variable that can be used to apply a padding-right to the position fixed elements inside the target.

ParameterTypeDefaultDescription
targetHTMLElementDocument.documentElement(Optional) The target Element.

Block Document HTML scroll when a popup is opened
const openPopUpHandler = () => {
  blockScroll()
  // ... handle popup
}
.modal-wrapper {
  position      : fixed;
  inset         : 0;
  padding-right : var( --scrollbar-size, 0 );
}

Block scroll of a specific HTMLElement
const element = document.querySelector( '.css-selector' )

if ( element ) {
  blockScroll( element )
}

restoreScroll

Restore Element Overflow.

ParameterTypeDefaultDescription
targetHTMLElementDocument.documentElement(Optional) The target Element.

Restore Document HTML scroll when a popup is closed
const closePopUpHandler = () => {
  // ... handle close
  restoreScroll()
}

Restore scroll of a specific HTMLElement
const element = document.querySelector( '.css-selector' )

if ( element ) {
  restoreScroll( element )
}

Generators utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/generators'

isGeneratorFunction

Check if a function is a GeneratorFunction or AsyncGeneratorFunction.

ParameterTypeDescription
referenceunknownThe function to check.

Type: reference is GeneratorFunction | AsyncGeneratorFunction

  • true if the given reference is a GeneratorFunction or AsyncGeneratorFunction.
  • false otherwise.

isDefaultGeneratorFunction

Check if a function is a GeneratorFunction.

ParameterTypeDescription
referenceunknownThe function to check.

Type: reference is GeneratorFunction

  • true if the given reference is a GeneratorFunction.
  • false otherwise.

isAsyncGeneratorFunction

Check if a function is an AsyncGeneratorFunction.

ParameterTypeDescription
referenceunknownThe function to check.

Type: reference is AsyncGeneratorFunction

  • true if the given reference is an AsyncGeneratorFunction.
  • false otherwise.

isGeneratorObject<T>

Check if reference is a Generator or AsyncGenerator.

ParameterTypeDescription
referenceunknownThe reference to check.

Type: reference is Generator<T> | AsyncGenerator<T>

  • true if the given reference is a Generator or AsyncGenerator.
  • false otherwise.

isDefaultGeneratorObject<T>

Check if reference is a Generator.

ParameterTypeDescription
referenceunknownThe reference to check.

Type: reference is Generator<T>

  • true if the given reference is a Generator.
  • false otherwise.

isAsyncGeneratorObject<T>

Check if reference is an AsyncGenerator.

ParameterTypeDescription
referenceunknownThe reference to check.

Type: reference is AsyncGenerator<T>

  • true if the given reference is an AsyncGenerator.
  • false otherwise.

Map utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/map'

Interface TypedMap<T, P, K>

A type-safe extension of the Map class that enforces key-value relationships based on a provided type.

ParameterTypeDefaultDescription
TRecord<string, unknown>unknownThe object type defining the key-value relationships.
PbooleantrueDefines whether the Map.get() method should return a possibily undefined value.
Kkeyof Tkeyof TInternal - The subset of keys in T that are allowed in the Map.

getTypedMap<T, P, K>

Creates a new instance of a type-safe Map with the given type.


ParameterTypeDescription
iterableIterable<readonly [ K, T[ K ] ]> \| nullInitial Map constructor iterable object.

Type: TypedMap<T, P, K>

A new instance of a type-safe Map.


Basic usage
interface User
{
  name      : string
  age       : number
  isActive  : boolean
}

const user = getTypedMap<User>( [
  [ 'name',     'Foo' ],
  [ 'age',      27 ],
  [ 'isActive', true ],
] )

console.log( user.get( 'name' ) ) // type: `string | undefined`
console.log( user.get( 'age' ) ) // type: `number | undefined`
console.log( user.get( 'isActive' ) ) // type: `boolean | undefined`

Respect the given type
interface User
{
  name      : string
  age       : number
  isActive  : boolean
  banned?   : boolean
}

const user = getTypedMap<User, false>( [
  [ 'name',     'Foo' ],
  [ 'age',      27 ],
  [ 'isActive', true ],
] )

console.log( user.get( 'name' ) ) // type: `string`
console.log( user.get( 'age' ) ) // type: `number`
console.log( user.get( 'isActive' ) ) // type: `boolean`
console.log( user.get( 'banned' ) ) // type: `boolean | undefined`

Promises utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/promises'

sleep

Await a void Promise that resolves after the given time.

ParameterTypeDescription
timenumberThe sleep time in milliseconds after the Promise get resolved.

Type: Promise<void>

A new Promise which get resolved after the specified time.


const fn = async () => {
  // ...
  await sleep( 2000 )
  // ...
}

Strings utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/strings'

ucFirst

Make first letter uppercase.

ParameterTypeDescription
inputstringThe input string to convert.

Type: string

The processed string.


console.log( ucFirst( 'String value' ) ) // Outputs: 'String value'
console.log( ucFirst( 'string value' ) ) // Outputs: 'String value'

lcFirst

Make first letter lowercase.

ParameterTypeDescription
inputstringThe input string to convert.

Type: string

The processed string.


console.log( lcFirst( 'String value' ) ) // Outputs: 'string value'
console.log( lcFirst( 'string value' ) ) // Outputs: 'string value'

toCamelCase

Convert string to camelCase.

ParameterTypeDescription
inputstringThe input string to convert.

Type: string

The converted string to camelCase.


console.log( toCamelCase( 'font-family' ) ) // Outputs: 'fontFamily'
console.log( toCamelCase( 'background-color' ) ) // Outputs: 'backgroundColor'
console.log( toCamelCase( '-webkit-align-content' ) ) // Outputs: 'WebkitAlignContent'
console.log( toCamelCase( 'some value' ) ) // Outputs: 'someValue'
console.log( toCamelCase( 'some_value' ) ) // Outputs: 'someValue'
console.log( toCamelCase( 'some value_with mixed_Cases' ) ) // Outputs: 'someValueWithMixedCases'
console.log( toCamelCase( '-string@with#special$characters' ) ) // Outputs: 'StringWithSpecialCharacters'

toKebabCase

Convert string to kebab-case string.

ParameterTypeDescription
inputstringThe input string to convert.

Type: string

The converted string to kebab-case.


console.log( toKebabCase( 'fontFamily' ) ) // Outputs: 'font-family'
console.log( toKebabCase( 'backgroundColor' ) ) // Outputs: 'background-color'
console.log( toKebabCase( 'string with spaces' ) ) // Outputs: 'string-with-spaces'
console.log( toKebabCase( 'string_with_underscores' ) ) // Outputs: 'string-with-underscores'
console.log( toKebabCase( 'WebkitAlignContent' ) ) // Outputs: '-webkit-align-content'
console.log( toKebabCase( 'some value_with mixed_Cases' ) ) // Outputs: 'some-value-with-mixed-cases'
console.log( toKebabCase( '-string@with#special$characters' ) ) // Outputs: '-string-with-special-characters

stringifyValue

Stringify value.

ParameterTypeDescription
inputanyThe value to stringify.

Type: string

The stringified input.


console.log( stringifyValue( new Date( 'Sat, 20 Apr 2025 16:20:00 GMT' ) ) )
// Outputs: '2025-04-20T16:20:00.000Z'

console.log( stringifyValue( null ) )
// Outputs: 'null'

console.log( stringifyValue( { prop: 'value', prop2: true } ) )
// Outputs: '{"prop":"value","prop2":true}'

console.log( stringifyValue( [ 1, 2, true, null, () => {} ] ) )
// Outputs: '[1,2,true,null,null]'

console.log( stringifyValue(
  new Map( [
    [ 'key', 'value' ],
    [ 'key2', 'value' ],
  ] )
) )
// Outputs: '[["key","value"],["key2","value"]]'

console.log( stringifyValue(
  new Headers( {
    key   : 'value',
    key2  : 'value',
  } )
) )
// Outputs: '[["key","value"],["key2","value"]]'

console.log( stringifyValue( true ) ) // Outputs: 'true'
console.log( stringifyValue( false ) ) // Outputs: 'false'
console.log( stringifyValue( 0 ) ) // Outputs: '0'
console.log( stringifyValue( 420 ) ) // Outputs: '420'

console.log( stringifyValue( undefined ) ) // Outputs: ''
console.log( stringifyValue( () => {} ) ) // Outputs: ''
console.log( stringifyValue( new Promise<void>( resolve => resolve() ) ) ) // Outputs: ''

parseValue

Parse stringified value.

ParameterDescription
TThe expected returned value type.

ParameterTypeDescription
inputstringThe value to parse.

Type: T | undefined

  • The parsed input.
  • undefined if no input or empty string is given.

console.log( parseValue<Date>( stringifyValue( new Date() ) ) )
// Outputs: current Date object.

console.log( parseValue<number>( '12345' ) ) // Outputs: 12345
console.log( parseValue() ) // Outputs: undefined
console.log( parseValue( ' ' ) ) // Outputs: undefined

console.log( parseValue<true>( stringifyValue( true ) ) )
// Outputs: true

console.log( parseValue( stringifyValue( { key: 'value' } ) ) )
// Outputs: { key: 'value' }

console.log( parseValue( stringifyValue( [ 1, 2, 3, 4, 5 ] ) ) )
// Outputs: [ 1, 2, 3, 4, 5 ]

console.log( parseValue( 'String value' ) ) // Outputs: 'String value'

Types utilities

⚠️ Docs coming soon


Validation utilities

⚠️ Docs coming soon


Browser API utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/browser-api'
getMediaMatches

Safely executes window.matchMedia() in server and browser environments.

ParameterTypeDescription
querystringThe Media Query string to check.

Type: boolean

  • false if window is not defined or if the document currently doesn't matches the given query.
  • true otherwise.

Check if current device is landscape oriented
console.log( ! getMediaMatches( '(orientation:portrait)' ) )

openBrowserPopUp

Opens a webpage in a browser PopUp.

The openBrowserPopUp uses Window.open() under the hood, but provides default options to make your work easier.

ParameterTypeDefaultDescription
optionsOpenBrowserPopUpOptions-An object defining custom PopUp options.
options.urlUrlInput-The URL or path of the resource to be loaded. See UrlInput for more info about accepted formats.
options.widthnumber600The PopUp width.
options.heightnumber800The PopUp height.
options.contextstring-A string, without whitespace, specifying the name of the browsing context the resource is being loaded into.
options.featuresOptionsFeatures-Additional custom PopUp features.

Type: WindowProxy | null

  • a WindowProxy object is returned if the browser successfully opens the new browsing context.
  • null is returned if the browser fails to open the new browsing context, for example because it was blocked by a browser popup blocker.

Re-focus a previously opened popup
let windowProxy: WindowProxy | null = null

const clickHandler = () => {
  if ( windowProxy && ! windowProxy.closed ) {
    return windowProxy.focus()
  }

  windowProxy = openBrowserPopUp( {
    url     : {
      pathname  : '/',
      query     : { key: 'value' }
    },
  } )
}

Re-use a popup
const clickHandler = () => {
  openBrowserPopUp( {
    context : 'some-context-name',
    url     : {
      pathname  : '/',
      query     : { key: 'value' }
    },
  } )
}


const clickHandler2 = () => {
  openBrowserPopUp( {
    context : 'some-context-name',
    url     : '/other-path',
  } )
}

Device utilities

Importing the utilitites
import { ... } from '@alessiofrittoli/web-utils'
// or
import { ... } from '@alessiofrittoli/web-utils/device'
isPortrait

Check if device is in portrait orientation.

Type: boolean

  • true if the device is in portrait orientation when this function is executed.
  • false otherwise.

Check if current device is landscape oriented
console.log( ! isPortrait() )

Storage utilities

Cookie Class
import { Cookie } from '@alessiofrittoli/web-utils'
// or
import { Cookie } from '@alessiofrittoli/web-utils/storage/Cookie'

import { Priority, SameSite } from '@alessiofrittoli/web-utils'
// or
import { Priority, SameSite } from '@alessiofrittoli/web-utils/storage/Cookie'

import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils'
// or
import type { RawCookie, ParsedCookie, ParsedCookieMap } from '@alessiofrittoli/web-utils/storage/Cookie'

Priority Enum

The Cookie Priority.

ConstantValueDescription
LowLowLow priority.
MediumMediumMedium priority (default).
HighHighHigh priority.

SameSite Enum

Controls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).

ConstantValueDescription
StrictStrictThe browser sends the cookie only for same-site requests.
LaxLaxThe cookie is not sent on cross-site requests, such as on requests to load images or frames, but is sent when a user is navigating to the origin site from an external site.
NoneNoneThe browser sends the cookie with both cross-site and same-site requests.

RawCookie<K, V>

Interface representing Cookie properties before it get parsed.

PropertyTypeDescription
nameKThe Cookie name.
valueVThe Cookie value.
domainstringDefines the host to which the cookie will be sent.
expiresstring \| number \| DateIndicates the maximum lifetime of the cookie.
httpOnlybooleanForbids JavaScript from accessing the cookie, for example, through the Document.cookie property.
maxAgenumberIndicates the number of seconds until the cookie expires. If set, expires is ignored.
partitionedbooleanIndicates that the cookie should be stored using partitioned storage.
pathstringIndicates the path that must exist in the requested URL for the browser to send the Cookie header.
sameSiteSameSiteControls whether or not a cookie is sent with cross-site requests, providing some protection against cross-site request forgery attacks (CSRF).
securebooleanIndicates that the cookie is sent to the server only when a request is made with the https: scheme.
priorityPriorityDefines the Cookie priority.

ParsedCookie<K, V>

Interface representing Cookie properties after it get parsed.

PropertyTypeDescription
expiresDateIndicates the maximum lifetime of the cookie.

ParsedCookieMap<K, V>

Map representation of a parsed Cookie.


Cookie.parse<K, V>()

Parse the given cookie parameters to a Cookie Map.

ParameterDescription
KThe typed cookie name.
VThe type of the cookie value.

ParameterTypeDescription
optionsRawCookie<K, V> \| ParsedCookieMap<K, V>The cookie options or a parsed Cookie Map.

Type: ParsedCookieMap<K, V>

The parsed Cookie Map.


const cookie = Cookie.parse( {
  name        : 'cookiename',
  value       : { test: 'value' },
  path        : '/specific-path',
  priority    : Priority.High,
  expires     : Date.now() + 20 * 60 * 1000,
  domain      : 'example.com',
  secure      : true,
  httpOnly    : true,
  sameSite    : SameSite.Lax,
  maxAge      : Date.now() + 30 * 60 * 1000,
  partitioned : true,
} )

Cookie.toString<K, V>()

Stringify a Cookie ready to be stored.

ParameterDescription
KThe typed cookie name.
VThe type of the cookie value.

ParameterTypeDescription
optionsRawCookie<K, V> \| ParsedCookieMap<K, V>The cookie options or a parsed Cookie Map.

Type: string

The stringified Cookie ready to be stored.


document.cookie = (
  Cookie.toString( {
    name        : 'cookiename',
    value       : { test: 'value' },
    path        : '/specific-path',
    priority    : Priority.High,
    expires     : Date.now() + 20 * 60 * 1000,
    domain      : 'example.com',
    secure      : true,
    httpOnly    : false,
    sameSite    : SameSite.Lax,
    maxAge      : Date.now() + 30 * 60 * 1000,
    partitioned : true,
  } )
)

Cookie.fromString<K, V>()

Parse a cookie string to a Cookie Map.

ParameterDescription
KThe typed cookie name.
VThe expected cookie value type.

ParameterTypeDescription
cookiestringThe cookie string.

Type: ParsedCookieMap<K, V> | null

The parsed Cookie Map or null if parsing fails.


const cookies = (
  document.cookie.split( '; ' )
    .map( Cookie.fromString )
    .filter( Boolean )
)

Cookie.fromListString<T, K>()

Parse a cookie list string to a Map of cookies.

ParameterDescription
TA Record o key-value pairs (key: cookie name, value: expected cookie value type).
KInternal.

ParameterTypeDescription
liststringThe cookie list string.

Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>

The Map of parsed cookies indexed by the Cookie name.


Defining custom types
/** On-site stubbed cookie names. */
enum CookieName
{
  COOKIE_1 = 'cookie-1',
  COOKIE_2 = 'cookie-2',
}

interface Cookie1
{
  test: 'value'
}

interface Cookie2
{
  test: boolean
}

type CookiesMap = {
  [ CookieName.COOKIE_1 ]: Cookie1
  [ CookieName.COOKIE_2 ]: Cookie2
}

Get parsed cookies from Document.cookie
const cookies     = Cookie.fromListString<CookiesMap>( document.cookie )
const cookie      = cookies.get( CookieName.COOKIE_1 ) // `ParsedCookieMap<CookieName.COOKIE_1, Cookie1> | undefined`
const cookieValue = cookie?.get( 'value' ) // `Cookie1 | undefined`

Get parsed cookies from a request Cookie header
const { headers } = request
const cookielist  = headers.get( 'Cookie' )

if ( cookielist ) {
  const cookies     = Cookie.fromListString<CookiesMap>( cookielist )
  const cookie      = cookies.get( CookieName.COOKIE_2 ) // `ParsedCookieMap<CookieName.COOKIE_2, Cookie2> | undefined`
  const cookieValue = cookie?.get( 'value' ) // `Cookie2 | undefined`
}

Cookie.get<T>()

Get a cookie by cookie name from Document.cookie.

ParameterDescription
TThe expected type for the Cookie value.

ParameterTypeDescription
namestringThe name of the cookie.

Type: ParsedCookieMap<typeof name, T> | undefined

  • The found parsed cookie.
  • undefined if no cookie has been found in Document.cookie.

const cookie  = Cookie.get<string>( 'access_token' )
const value   = cookie?.get( 'value' ) // `string | undefined`

Cookie.getAll<T>()

Get a Map of all cookies found in Document.cookie.

ParameterDescription
TA Record o key-value pairs (key: cookie name, value: expected cookie value type).

Type: TypedMap<{ [P in K]: ParsedCookieMap<P, T[P]>; }>

The Map of parsed cookies indexed by the Cookie name.


const cookies = Cookie.getAll()
const cookie  = cookies.get( 'somecookie' )
Cookie.set<K, V>()

Set a cookie to Document.cookie.

ParameterDescription
KThe typed cookie name.
VThe cookie value type.

ParameterTypeDescription
optionsRawCookie<K, V> \| ParsedCookieMap<K, V>The cookie options or a parsed Cookie Map.

Type: ParsedCookieMap<K, V> | false

  • The set Cookie Map if successful.
  • false on failure.

const cookieOptions: RawCookie = {
  name        : 'cookiename',
  value       : { test: 'value' },
  path        : '/specific-path',
  priority    : Priority.High,
  expires     : Date.now() + 20 * 60 * 1000,
  domain      : 'example.com',
  secure      : true,
  httpOnly    : false,
  sameSite    : SameSite.Lax,
  maxAge      : Date.now() + 30 * 60 * 1000,
  partitioned : true,
}

Cookie.set( cookieOptions )
// or
Cookie.set( Coookie.parse( cookieOptions ) )

Cookie.delete()

Delete a cookie by cookie name from Document.cookie.

ParameterTypeDescription
namestringThe cookie name to delete.

Type: boolean

  • true on successfull.
  • false on failure.

Cookie.delete( 'some_cookie' )

LocalStorage Class

A browser-compatible implementation of localStorage.

import { LocalStorage } from '@alessiofrittoli/web-utils'
// or
import { LocalStorage } from '@alessiofrittoli/web-utils/storage/LocalStorage'

LocalStorage.key()

Get storage item name by item numeric index.

ParameterTypeDescription
indexnumberThe item index in the storage.

Type: string | null

  • The name of the nth key.
  • null if n is greater than or equal to the number of key/value pairs.

console.log( LocalStorage.key( 0 ) ) // Outputs: first item name if any.

LocalStorage.getLength()

Get the number of key/value pairs.

Type: number

The number of key/value pairs.


console.log( LocalStorage.getLength() )

LocalStorage.get<T>()

Get the current value associated with the given key, or undefined if the given key does not exist.

ParameterDescription
TThe expected item value type.

ParameterTypeDescription
keystringThe item name.

Type: T | undefined

  • The current value associated with the given key.
  • undefined if the given key does not exist.

LocalStorage.get<Date>( 'expiration' )

LocalStorage.set<T>()

Sets the value of the pair identified by key to value, creating a new key/value pair if none existed for key previously.

Dispatches a storage event on Window objects holding an equivalent Storage object.

If a nullish or empty string value is provided, the LocalStorage.delete() method is invoked.

ParameterDescription
TThe item value type.

ParameterTypeDescription
keystringThe item name.
valueTThe item value.

Type: DOMException

A "QuotaExceededError" DOMException exception if the new value couldn't be set. (Setting could fail if, e.g., the user has disabled storage for the site, or if the quota has been exceeded.)


LocalStorage.set<Date>( 'expiration', new Date() )

LocalStorage.delete()

Removes the key/value pair with the given key, if a key/value pair with the given key exists.

Dispatches a storage event on Window objects holding an equivalent Storage object.

ParameterTypeDescription
keystringThe item name.

LocalStorage.delete( 'expiration' )

LocalStorage.clear()

Removes all key/value pairs, if there are any.

Dispatches a storage event on Window objects holding an equivalent Storage object.

LocalStorage.clear()

SessionStorage Class

A browser-compatible implementation of sessionStorage.

Same API References of LocalStorage Class is applied to the SessionStorage Class.

Please, refer to LocalStorage Class static methods API Reference for more informations.

import { SessionStorage } from '@alessiofrittoli/web-utils'
// or
import { SessionStorage } from '@alessiofrittoli/web-utils/storage/SessionStorage'

Development

Install depenendencies

npm install

or using pnpm

pnpm i

Build the source code

Run the following command to test and build code for distribution.

pnpm build

ESLint

warnings / errors check.

pnpm lint

Jest

Run all the defined test suites by running the following:

# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci

Run tests with coverage.

An HTTP server is then started to serve coverage files from ./coverage folder.

⚠️ You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.

test:coverage:serve

Contributing

Contributions are truly welcome!

Please refer to the Contributing Doc for more information on how to start contributing to this project.

Help keep this project up to date with GitHub Sponsor.

GitHub Sponsor


Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email security@alessiofrittoli.it to disclose any security vulnerabilities.

Made with ☕

1.12.0

10 months ago

1.11.0

10 months ago

1.10.0

11 months ago

1.9.1

11 months ago

1.9.0

11 months ago

1.8.1

11 months ago

1.8.0

11 months ago

1.7.0

11 months ago

1.6.0

11 months ago

1.5.1

12 months ago

1.5.0

12 months ago

1.4.0

12 months ago

1.3.0

12 months ago

1.2.0

1 year ago

1.1.2

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.0

1 year ago

0.8.1

1 year ago

0.8.0

1 year ago

0.7.0

1 year ago

0.6.0

1 year ago

0.5.0

1 year ago

0.4.0

1 year ago

0.3.0

1 year ago

0.2.0

1 year ago

0.1.0

1 year ago