npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@substrate-system/util

v0.1.35

Published

Utility functions

Readme

util

tests types module semantic versioning dependencies install size license

Utility functions for the front end.

install

npm i -S @substrate-system/util

import

import util from '@substrate-system/util'

// or individual functions
import { attributesToString } from '@substrate-system/util'

API

toString

Convert an object into a string suitable for HTML attributes. The object should be like { attributeName: value }. value can be and array, string, or boolean. If it is a boolean, then this will add the attribute name only, eg

import { attributes } from '@substrate-system/util/to-string.js'

attributes({ disabled: true })
// => 'disabled'
import { attributes } from '@substrate-system/util/to-string.js'

const string = attributes({ hello: 'abc', ok: '123' })

// => 'hello="abc" ok="123"'
import { attributes } from '@substrate-system/util/to-string.js'

test('Create attributes with null and undefined', t => {
    const str = attributes({
        hello: 'abc',
        abc: undefined,
        def: null,
        ghi: false,
        jkl: ''
    })

    t.equal(str, 'hello="abc"')
})

lock & unlock scrolling

Prevents body scrolling, useful for things like "dialog" windows. Keeps track of which elements requested a lock so multiple levels of locking are possible without premature unlocking.

Originally seen in the shoelace library.

CSS

Depends on having this CSS:

@supports (scrollbar-gutter:stable) {
    .scroll-lock body {
        overflow: hidden !important;
    }
}

Import from here to add it:

import '@substrate-system/util/css/scroll'

example

import {
    lockBodyScrolling,
    unlockBodyScrolling
} from '@substrate-system/util/scroll'

// stop scroll
lockBodyScrolling(document.body)

// ...sometime in the future...
unlockBodyScrolling(document.body)

lockBodyScrolling

Stop scrolling.

function lockBodyScrolling (lockingEl:HTMLElement):void

unlockBodyScrolling

Resume scrolling.

function unlockBodyScrolling (lockingEl:HTMLElement):void

Constants

Various special characters.

const EM_DASH = '\u2014'
const EN_DASH = '\u2013'
const NBSP = '\u00A0'
const PETABYTE = (2 ** 50)
const TERABYTE = (2 ** 40)
const GIGABYTE = (2 ** 30)
const MEGABYTE = (2 ** 20)
const KILOBYTE = (2 ** 10)
const ELLIPSIS = '\u2026'
const BULLET = '\u2022'
import { ELLIPSIS } from '@substrate-system/util/constants'

element.textContent = `${ELLIPSIS} something dramatic ${ELLIPSIS}`

HTML classes

Create a new class name string by concattenating the given input.

import { classes } from '@substrate-system/util/classes'
const className = classes('hello', '123', '100')
// => 'hello 123 100'

self

The self object for Node.

import { self } from '@substrate-system/util/node'

humanFilesize

Take the number of bytes, return a string abbreviated to common sizes (megabyte, kilobyte, etc).

Example

import { humanFilesize } from '@substrate-system/util/filesize'

const size = humanFilesize(10_000)
console.log(size)
// => 9.8 KiB

API

function humanFilesize (
    bytes:number,
    si:boolean = false,
    dp:number = 1
):string
arguments
  • bytes the byte count
  • si -- use SI, instead of EIC units (default false)
  • dp is the number of decimal places to show.

Queue

import { Queue } from '@substrate-system/util/queue'

Create a queue of promises. Promises will execute 1 at a time, in sequential order.

class Queue<T> {
    add (createP:()=>Promise<T>):Promise<T|void>
}

queue.add

Take a function that returns a promise. Return a promise that will resolve when the created promise resolves.

add (createP:()=>Promise<T>):Promise<T|void>

[!NOTE]
This will resolve promises in the order they were added to the queue.

example

import { test } from '@substrate-system/tapzero'
import { Queue } from '@substrate-system/util'

test('queue of 3 items', t => {
    const q = new Queue<string>()

    // [p1, p2, p3]
    const returned = [false, false, false]

    const p1 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p1'), 300)
        })
    })

    const p2 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p2'), 200)
        })
    })

    const p3 = q.add(() => {
        return new Promise<string>(resolve => {
            setTimeout(() => resolve('p3'), 100)
        })
    })

    // p1 takes the longest
    p1.then((value) => {
        t.equal(value, 'p1', '"p1" string is ok')
        returned[0] = true
        t.ok(!returned[2], 'p2 should not have returned yet')
        t.ok(!returned[1], 'p1 should not have returned yet')
    })

    p2.then(value => {
        t.equal(value, 'p2', 'should get string "p2"')
        returned[1] = true
        t.ok(returned[0], 'should have p1 b/c it was added first')
        t.ok(!returned[2], 'should not have 3 yet b/c it was addded last')
    })

    // p3 is the fastest
    p3.then(value => {
        t.equal(value, 'p3', 'should get string "p3"')
        returned[2] = true
        t.ok(returned[0], 'should have p1 because it was added first')
        t.ok(returned[1], 'should have p2 because it was added next')
    })

    // return 3 so the test knows when to end,
    // because they resolve in order,
    // even though the ms are backwards
    return p3
})

sleep

Import sleep from here to reduce duplication.

function sleep (ms?:number):Promise<void>
import { sleep } from '@substrate-system/util'

await sleep(500)  // 1/2 second

isEmailValid(maybeEmail:string)

Validate an email address.

function isEmailValid (maybeEmail:string):boolean

example

import { isEmailValid } from '@substrate-system/util/email'

isEmailValid('[email protected]')
// => true

parseForm

Parse a form and return a plain object. If a form control with the same name appears more than once, the property will be converted to an array.

function parseForm (form:HTMLFormElement):Record<string, unknown>

attributesToString

Take an array of attributes, and transform them into a string format. This can be useful for creating web components.

function attributesToString (attrs:Attr[]):string {

example

import { attributesToString } from '@substrate-system/util'

const el = document.getElementById('example')
const str = attributesToString(Array.from(el!.attributes))
console.log(str)
// => 'type="text" id="example" required'

setAttributes

Set the given attributes from an object. Will handle boolean attributes like required.

function setAttributes (el:HTMLElement, attrs:Record<string, string|boolean>)
import { attributesToString, setAttributes } from '@substrate-system/util'

const input = document.getElementById('test') as HTMLInputElement

setAttributes(input, {
    id: 'test',
    required: true,
    name: 'fooo',
    class: 'testing'
})

console.log(attributesToString(Array.from(input.attributes)))
// => 'id="test" class="testing" name="fooo" required',

attributesAsObject

Return an object of { key: value } from an array of attributes. If an attribute is a boolean value, then it will be { name: true }.

function attributesAsObject (attrs:Attr[]):Record<string, string|true>
import { attributesAsObject } from '@substrate-system/util'

const el = document.querySelector('input')
const attrs = Array.from(el!.attributes)
const obj = attributesAsObject(attrs)
console.log(obj)
// => {
//   "type": "text",
//   "required": true,
//   "name": "example",
//   "foo": "bar"
// }

objectToString

Take an object, as from attributesAsObject, and stringify it for use in HTML.

function objectToString (obj:Record<string, string|true>):string
import { objectToString } from '@substrate-system/util'

const obj =  {
    type: "text",
    required: true,
    name: "example",
    foo: "bar"
}
const str = objectToString(obj)
console.log(str)
// => 'type="text" required name="example" foo="bar"'

CONSTANTS

Expose unicode characters.

import * as CONSTANTS from '@substrate-system/util/CONSTANTS'
// CONSTANTS.ts
export const EM_DASH = '\u2014'
export const EN_DASH = '\u2013'
export const NBSP = '\u00A0'