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

type-checking-functions

v1.1.4

Published

A collection of TypeScript utility functions for common programming tasks including validation, string manipulation, and async operations.

Readme

TypeScript Utility Functions

those are basic but most powerful common functions

Usage

Import the functions you need:


import {isNullOrUndefined,handleAsync,isEmptyString,isObjectEmpty,
isValidCursor,isValidPassword,validateEmail,GenerateUID,
GenerateOtp,capitalizeWords,formatBytes,getRandomColor,
queryToObject,createUniqueArrayStore,mergeSort,colorfulLog,
useDebounce,useThrottle,HybridFetch,ObjectToArray,ArrayToObject,
flattenArray,sanitizeText,getQuery,getDayName,
getOnlyDate} from 'type-checking-functions'

Functions

Validation Functions

isNullOrUndefined(value: any): boolean

Checks if a value is null or undefined.

console.log(isNullOrUndefined(null));      // true
console.log(isNullOrUndefined(undefined)); // true
console.log(isNullOrUndefined(''));        // false

isEmptyString(value: any): boolean

Checks if a value is an empty string.

console.log(isEmptyString(''));     // true
console.log(isEmptyString('  '));   // true
console.log(isEmptyString('text')); // false

isObjectEmpty(obj: Record<string, any>): boolean

Checks if an object has no properties.

console.log(isObjectEmpty({}));              // true
console.log(isObjectEmpty({ key: 'value' })); // false

validateEmail(email: string): boolean

Validates email addresses.

console.log(validateEmail('[email protected]'));  // true
console.log(validateEmail('invalid.email'));     // false

isValidPassword(password: string): boolean

Checks if a password meets security requirements (8+ characters, contains letters and numbers).

console.log(isValidPassword('Pass123!'));  // true
console.log(isValidPassword('weak'));      // false

isValidCursor(cursor: any): boolean

Validates cursor values for pagination.

console.log(isValidCursor(1));        // true
console.log(isValidCursor(0));        // false
console.log(isValidCursor('abc'));    // true
console.log(isValidCursor(''));       // false

Async Operations

handleAsync<T>(promise: Promise<T>): Promise<[T | null, any]>

Handles async operations with error catching.

const fetchData = async () => {
  const [data, error] = await handleAsync(fetch('https://api.example.com/data'));
  if (error) {
    console.error('Error fetching data:', error);
    return;
  }
  console.log('Data:', data);
};

Generation Functions

GenerateUID(): string

Generates a UUID using crypto.randomUUID().

console.log(GenerateUID()); // e.g., "123e4567-e89b-12d3-a456-426655440000"

GenerateOtp(length: number = 6, isMixed: boolean = false): string

Generates one-time passwords.

console.log(GenerateOtp());           // e.g., "123456"
console.log(GenerateOtp(4));          // e.g., "1234"
console.log(GenerateOtp(6, true));    // e.g., "A1b2C3"

String Manipulation

capitalizeWords(str: string): string

Capitalizes the first letter of each word.

console.log(capitalizeWords('hello world')); // "Hello World"

queryToObject(query: string): Record<string, string>

Converts URL query strings to objects.

console.log(queryToObject('?name=John&age=30'));
// { name: 'John', age: '30' }

Formatting

formatBytes(bytes: number, decimals: number = 2): string

Converts bytes to human-readable format.

console.log(formatBytes(1234));        // "1.21 KB"
console.log(formatBytes(1234567));     // "1.18 MB"

getRandomColor(): string

Generates random hex color codes.

console.log(getRandomColor()); // e.g., "#ff4521"

createUniqueArrayStore<T extends Record<string, any>>(uniqueKey: keyof T)

Creates a store that maintains unique objects, ensuring that no duplicate objects (based on a specified unique key) are added. It provides various methods to interact with the store, such as adding, removing, and querying objects.

Parameters:

  • uniqueKey: The key that should be unique for each object in the store. This key is used to ensure that objects are not duplicated.

Methods:

  • push(obj: T): Adds an object to the store if it has a unique key.
  • pop(): Removes and returns the last added object from the store.
  • get(key: T[keyof T]): T | undefined: Retrieves an object based on the unique key.
  • has(key: T[keyof T]): boolean: Checks if an object exists with the given unique key.
  • delete(key: T[keyof T]): Deletes an object based on the unique key.
  • size(): number: Returns the number of objects in the store.
  • clear(): Clears the store, removing all objects.
  • values(): T[]: Returns all objects in the store as an array.
  • map<U>(callback: (value: T, index: number, array: T[]) => U): U[]: Maps over the store and returns a new array.
  • filter(callback: (value: T, index: number, array: T[]) => boolean): T[]: Filters the store based on a condition.
  • forEach(callback: (value: T, index: number, array: T[]) => void): Iterates over the store and executes a callback.
  • find(callback: (value: T, index: number, array: T[]) => boolean): T | undefined: Finds the first object that matches the condition.

Example Usage:

const store = createUniqueArrayStore<{ id: number; name: string }>('id');
store.push({ id: 1, name: 'Alice' });
store.push({ id: 2, name: 'Bob' });
console.log(store.get(1)); // { id: 1, name: 'Alice' }
console.log(store.size()); // 2
store.pop(); // Removes { id: 2, name: 'Bob' }

ObjectToArray



const obj = {
  name: 'John',
  age: 30,
  country: 'USA',
};

const result = ObjectToArray(obj);
console.log(result);
// Output: [["name", "John"], ["age", 30], ["country", "USA"]]

ArrayToObject



const arr = [
  ['name', 'John'],
  ['age', 30],
  ['country', 'USA'],
];

const result = ArrayToObject(arr);
console.log(result);
// Output: { name: 'John', age: 30, country: 'USA' }

sanitizeText



const input = '<script>alert("hack!")</script><p>Hello, world!</p>';
const sanitized = sanitizeText(input);

console.log(sanitized);
// Output: "Hello, world!"

getOnlyDate

Description

The getOnlyDate function extracts the date part from a Date object and returns it in ISO string format (YYYY-MM-DD).

Example Usage:

import { getOnlyDate } from './path-to-your-function';

const date = new Date('2025-02-22T12:34:56Z');
const result = getOnlyDate(date);

console.log(result); 
// Output: "2025-02-22"

flattenArray



const nestedArray = [1, [2, [3, 4], 5], 6];
const result = flattenArray(nestedArray);

console.log(result); 
// Output: [1, 2, 3, 4, 5, 6]

getDayName



const date = new Date('2025-02-22');
const result = getDayName(date);

console.log(result); 
// Output: "Saturday"

getQuery

const queryParams = {
    search: 'query',
    page: 2,
    filter: null,
};

const result = getQuery(queryParams);

console.log(result); 
// Output: "search=query&page=2"

mergeSort Utility

The `mergeSort` function is a custom implementation of the **merge sort algorithm**, which is a highly efficient, stable, and comparison-based sorting algorithm. It recursively divides the input array into smaller subarrays, sorts them, and then merges them back together in the correct order based on the comparison function provided.

## Function: `mergeSort<T>(arr: T[], compareFn: (a: T, b: T) => number): T[]`

Sorts an array using the merge sort algorithm with a custom comparison function.

### Parameters:

- `arr`: The array of type `T` to be sorted.
- `compareFn`: A comparison function that determines the sort order. It takes two arguments, `a` and `b` (elements of the array), and returns:
  - A **negative number** if `a` should come before `b`,
  - Zero if `a` and `b` are equal,
  - A **positive number** if `a` should come after `b`.

### Returns:
- A new array containing the sorted elements.

### Example Usage:

Sorting numbers in ascending order:


```typescript
const numbers = [5, 2, 8, 1, 3];
const sortedNumbers = mergeSort(numbers, (a, b) => a - b);
console.log(sortedNumbers); // [1, 2, 3, 5, 8]

# colorfulLog Utility

The `colorfulLog` function is a utility designed to log messages to the console with a colorful and customizable output. It enables users to easily highlight key-value pairs in the console with custom background colors and styles for better visibility and debugging.

## Function: `colorfulLog(value: any, key?: string, keyColor = "578FCA", valueColor = "4DA1A9")`

Logs a message to the console with a specified color scheme for the key and value.

### Parameters:

- `value`: The value to log, which can be any type (string, object, number, etc.).
- `key` *(optional)*: The key or label for the value (e.g., 'Error', 'Info', etc.).
- `keyColor` *(optional)*: The hexadecimal color code for the key’s background. Default is `#578FCA` (a blue color).
- `valueColor` *(optional)*: The hexadecimal color code for the value’s background. Default is `#4DA1A9` (a teal color).

### Returns:
- `undefined` (This function doesn't return anything; it simply logs to the console).

### Example Usage:

#### Logging a simple key-value pair:```


```typescript
colorfulLog("Hello World", "Greeting");


# `HybridFetch`

## Description
`HybridFetch` is a function that creates an instance of a dynamic fetch manager.  
It allows for making HTTP GET requests while automatically canceling any previous ongoing request.  
This ensures that only the latest request is processed, which is useful for real-time data fetching.

---

## Usage
```ts
import { HybridFetch } from "./utils";

const fetchData = HybridFetch();

// Fetching data
fetchData("https://api.example.com/data")
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

// Fetching with headers
fetchData("https://api.example.com/protected", {
  headers: {
    Authorization: "Bearer YOUR_TOKEN",
  },
})
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

// If a new request is made before the previous one completes, the previous request is automatically canceled.