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

utils-stuff

v5.0.0

Published

Generic utils, both for server or client uses

Readme

Utils Stuff

v5.0.0

This is a package i made for myself but can surely be helpful to others, feel free to contribute if you like it.

Install:

npm install utils-stuff

You can import the class GenericUtils and the function autobind (it is this exact code).

GenericUtils has some generic utils and a logger that better format the logs (with color too if you want).
autobind lets you bind all your class methods to its original instance (allowing both override and correct heritage)

At the moment, the interface of the class is as it follows:

export interface IGenericUtils {
    date: (date?:string, format?:string, locale?:DateLocales) => string
    resOk: <T>(response:T) => CatchedResponse<T>
    resError:(err:any) => CatchedResponse<any>
    getErrorMessage: (err:any) => string;
    catchReturn<T>(cb: () => Promise<T>, errorCb?:() => void): Promise<CatchedResponse<T>>;
    catchReturn<T>(cb: () => T, errorCb?:() => void): CatchedResponse<T>;
    isAxiosOk: (res:{ status:number, [Key:string]: GenericType} /* pass an AxiosResponse */) => boolean;
    isStringValid: (str?:string) => boolean;
    arrayDiff: <T = string | number>(originalArray:T[], currentArray:T[]) => ArrayDifference<T>;
    isNumeric: (str:string) => boolean;
    capitalize: (str:string, all?:boolean) => string;
    fromLetterToNumber: (char:string) => number;
    isEmptyObject: (obj:Record<string, any>) => boolean;
    getRandomColor: () => string;
    flattenObject: (obj:Record<string, any>) => Record<string, any>;
    sortObjects: <T = any>(arr:Array<Record<string, T>>, key:string | number) => Array<Record<string, T>>;
    keepTrying: <T = void>(finalError:string, methods: Array<() => Promise<T>>) => Promise<T>;
    sleep: (ms:number) => Promise<void>
    random: <T = any>(arr:Array<T>) => T
    fromStringToColor: (input:string, brightness:number) => string
}

Initialize the class

import { GenericUtils } from "utils-stuff"

The constructor of GenericUtils follows this interface:

protected readonly dateLocale:DateLocales = "en-US";
protected readonly isNumericRegex:RegExp = /^-?\d+(\.\d+)?$/
constructor(constructor?:GenericUtilsConstructor)
export interface GenericUtilsConstructor {
    locale?:DateLocales,
    numericValidation?:RegExp,
    defaultDateFormat?:string // for date parsing, default is "YYYY-MM-DD hh:mm:ss"
}

I suggest you to create a generic utils class extending mine if you want a solid way to store all your utils functions or whatever.

import { GenericUtils } from "utils-stuff";

// Create a class extending mine if you want to store other utils
class MyGenericUtils extends GenericUtils {
	myCustomMethod = (name:string):string => {
		return `Hello ${name}`
	}
}
const mgu = new MyGenericUtils(/*{ locale: "it-IT" }*/)


// Or simply export mine directly
const gu = new GenericUtils(/*{ locale: "it-IT" }*/)

Export it however you want but i raccomand you to init a single object and use it through all the project.

export default new GenericUtils(/*{ locale: "it-IT" }*/)

// Or destruct the single functions
const { resOk, resError, isStringValid } = new GenericUtils();
export { resOk, resError, isStringValid }

Methods

The related methods are really simple and can be easily read in the realted /package/src/GenericUtils.ts file in this repo.
The only methods not-so-easy to read are the date method and the isNumeric RegExp wich will return true if the passed string is any int, float, double or negative number. You can override the default regex in the constructor.

date: (date?:string|number|Date|null, format?:string, locale?:DateLocales) => string

This method takes a string or number that you would normally pass to a Date() constructor and an additional string param that let you format the date object into the string you want.
If no locale parameter is passed, it will be used the one specified in the constructor of the class GenericUtils({ locale:"..." }).
If no locale is passed in the class constructor it will be used "en-US"

See the related locale options in ./package/types/dater.types.ts

export type FormatUnit =
    | "YYYY"      // Year 4 digits (1996)
    | "YYY"       // Year 3 digits (996)
    | "YY"        // Year 2 digits (96)
    | "M"         // Month of year (1-12)
    | "MM"        // Month of year (01-12)
    | "MMM"       // Month of year (May) (set locale option)
    | "D"         // Day of month  (1-31)
    | "DD"        // Day of month  (01-31)
    | "DDD"       // Day of month  (Monday-Sunday) (set locale option)
    | "H"         // Hour of day   (0-23:59)
    | "HH"        // Hour of day   (00-23:59)
    | "h"         // Hour of day   (0-11:59)
    | "hh"        // Hour of day   (00-11:59)
    | "tt"        // AM or PM      (AM - PM)
    | "m"         // Minute        (0-59)
    | "mm"        // Minute        (00-59)
    | "s"         // Second        (0-59)
    | "ss"        // Second        (00-59)
    | "f"         // Milliseconds  (0000-999)
// --- Null or undefined is gonna be the current time
gu.date()
gu.date(null, "DDD DD, MMM YYYY")
gu.date(null, "DDD DD, MMM YYYY", "ru-RU")
gu.date(null, "hh:mm:ss:f")
gu.date(null, "MMM DD h.tt")
gu.date(1221732346340, "YYYY-MM-DD HH:mm:ss")
gu.date(new Date("2023/01/01"), "DD/MM/YY h:mm tt")
gu.date('2023-11-12T19:37:14.157Z', "DDD DD-MM-YYYY, h:mm tt")

keepTrying: <T = void>(finalError:string, methods: Array<() => Promise<T>>) => Promise<T>;

This methods helps use assign a variable by trying/catching multiple functions that return the same value type (you can set two datatypes in | with typescript). It takes two parameters:

  1. finalError:

If everything will go wrong it'll throw an error with your string as a message.

  1. methods:

A list of methods that possibly (encouraged) return the same datatype.

This is a random example

let compressedImageBytes = await keepTrying<Buffer>(`IMAGE == ${imagePath} == IS NOT JPG OR PNG`, [
    async () => await sharp(imagePath).jpeg({ quality:this.jpgCompression }).toBuffer(),
    async () => await sharp(imagePath).png({ compressionLevel: this.pngCompression }).toBuffer()
]);