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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@alius/utils

v1.0.6

Published

Utilities

Downloads

3

Readme

Various utilities - classes with static getters and methods.

Installation

npm install @alius/utils

API

EnvUtils

Properties

isBrowser

Returns true if code is running in browser environment.

isNode

Returns true if code is running in Node.js environment.

isDeno

Returns true if code is running in Deno environment.

StringUtils

Properties

HTML_CHAR_MAP

Map of characters to HTML

XML_CHAR_MAP

Map of characters to XML

Methods

escapeHtml(text)

Escapes special characters so it is safe to add text to html as value. Replaces following characters: & < > " ' \ \n \r \t \u2028 \u2029. If parameter is not string - it is converted to string before escaping. Returns empty string if parameter is null or undefined.

escapeXml(text)

Escapes special characters so it is safe to add text to xml as value. Replaces following characters: & < > " ' If parameter is not string - it is converted to string before escaping. Returns empty string if parameter is null or undefined.

escapeRegExp(text)

Escapes RegExp control characters. If parameter is not string - it is converted to string before escaping. Returns empty string if parameter is null or undefined.

pretty(object, indent, indentLevel = 2)

Converts provided value to pretty string. Object properties and array elements can be indented with specified number of spaces.

toUTF8Bytes(text)

Converts string to array of UTF-8 bytes.

fromUTF8Bytes(bytes)

Converts array of UTF-8 bytes to string.

fromBase64(text)

Decodes base64 encoded string.

toBase64(bytes)

Encodes byte array to base64 string.

fromBase64url(text)

Decodes base64url encoded string.

toBase64url(bytes)

Encodes byte array to base64url string.

ObjectUtils

Types

Cloner

  • test: (value: any) => boolean - function tests wether this cloner should be used
  • clone: (value: any, cloners: Array<Cloner>, path: Array<[any, any]>) => any - function clones provided value

Cloner type. Objects of this type are used in ObjectUtils.deepClone() to clone provided values. cloner.test() is used to test if this cloner should be used to clone specified value. cloner.clone() should clone provided value. If you need deep clone any internal property - add original and cloned values to path and pass cloners and path params further down eg:

const cloned = {};
path.push([orig, cloned]);
cloned.internal1 = ObjectUtils.deepClone(orig.internal1, cloners, path);
cloned.internal2 = ObjectUtils.deepClone(orig.internal2, cloners, path);

Methods

deepFreeze(o)

Deep freezes provided object. If provided object is array - deep freezes all elements of that array. If provided object is Set - deep freezes all elements of that set. If provided object is Map - deep freezes all keys and values of that map. If provided object is Object - deep freezes all values of that object.

filter(obj, props = [])

Makes shallow object copy with only specified properties.

const o = {
  prop1: 1,
  prop2: "Hello",
  prop3: true
};
console.log(ObjectUtils.filter(o, ["prop1", "prop3"])) // {prop1: 1, prop3: true}

If obj is not an object - returns obj. If props is empty - returns shallow copy of provided object. If props is specified - returned object will contain only properties specifed in it.

deepClone(object, cloners = [])

Deep clones specified object. Supports following types:

  • undefined - undefined
  • null - null
  • boolean - boolean
  • number - number
  • bigint - bigint
  • string - string
  • symbol - Does not clone: returns same Symbol object
  • function - Does not clone: returns same function object. Covers AsyncFunction, AsyncGeneratorFunction, GeneratorFunction
  • BigInt - Wrapper for primitive. Does not clone: returns same object
  • Boolean - Wrapper for primitive. Does not clone: returns same object
  • Number - Wrapper for primitive. Does not clone: returns same object
  • String - Wrapper for primitive. Does not clone: returns same object
  • Symbol - Wrapper for primitive. Does not clone: returns same object
  • Atomics - JS defined object. Does not clone: returns same object
  • globalThis - JS defined object. Does not clone: returns same object
  • Intl - JS defined object. Does not clone: returns same object
  • JSON - JS defined object. Does not clone: returns same object
  • Math - JS defined object. Does not clone: returns same object
  • Reflect - JS defined object. Does not clone: returns same object
  • Error - Does not clone: returns same object. Covers all instances of Error
  • ArrayBuffer|SharedArrayBuffer - new object with copied underlying buffer
  • DataView - new object with copied underlying buffer
  • TypedArray - new object with copied underlying buffer. Covers following typed buffers: BigInt64Array, BigUint64Array, Float32Array, Float64Array, Int16Array, Int32Array, Int8Array, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray
  • AsyncGenerator|Generator - Does not clone: returns same object
  • FinalizationRegistry|WeakSet|WeakMap|WeakRef - Does not clone: returns same object
  • Promise - Does not clone: returns same object
  • Date - new Date created with same getTime() as original
  • RegExp - new RegExp created with same pattern and flags as original
  • Set - new Set with deep cloned elements
  • Array - new Array with deep cloned elements
  • Map - new Map with deep cloned keys and deep cloned values.
  • Object - new Object with same prototype and deep cloned own properties.

Proxy instances are cloned as normal instances because there is no official way to identify is provided object is a proxy or not Handles circular references: keeps track of all traversed objects and their respective clones; if encounters reference to already traversed object - returns it's respective clone.

class Person {
  #firstName;
  #lastName;
  constructor(firstName, lastName) {
    this.#firstName = firstName;
    this.#lastName = lastName;
  }
  get fullName() {
    return this.#firstName + " " + this.#lastName;
  }
  clone() {
    return new Person(this.#firstName, this.#lastName);
  }
}

const o = {
  person: new Person("John", "Doe"),
  title: "worker",
  started: new Date("2023-01-01"),
  manager: new Person("Jane", "Smith")
};

const oc = ObjectUtils.deepClone(o, [{
  test: value => value instanceof Person,
  clone: value => value.clone()
}]);

getPathValue(obj, path)

Retrieves value from provided object via specified path. If provided path is empty - returns initial obj value. If provided path can not be traversed - returns undefined.

const o = {
  prop1: [
    1,
    {
      prop: "Hello"
    },
    false
  ],
  prop2: "World"
};

console.log(ObjectUtils.getPathValue(o, "prop1[0]")) // 1
console.log(ObjectUtils.getPathValue(o, "prop1[1].prop")) // Hello
console.log(ObjectUtils.getPathValue(o, "prop2")) // World

ClassUtils

Types

ClassDescriptorType

  • module: string - module name
  • class?: string - class name
  • method?: string - method name

Class descriptor type. Objects of this type can be used to load classes with Utils.loadClass().

Methods

isClassDescriptor(descriptor)

Tests is provided object is instance of ClassDescriptorType

loadClass(descriptor)

Loads class. Local module (name starts with ./ or ../) will be loaded relative to current working directory. Otherwise module (from node_modules) will be loaded. If descriptor contains property class then it will be used to select specific class from module export otherwise default export will be used.

importTextModule(jsCode)

Loads javascript source code as module (import).

const code = `
export const hi = "Hello world";
export function sum(a, b) {
  return a + b;
}
`;
const module = await ClassUtils.importTextModule(code);
console.log(module.hi); // Hello world
console.log(module.sum(1, 2)); // 3