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 🙏

© 2026 – Pkg Stats / Ryan Hefner

common-needs

v1.11.14

Published

A collection of simple utils that fulfill common needs

Downloads

122

Readme

Common Needs

Common Needs is just a personal JavaScript library I'm making to make faster/easier some simple tasks that can feel repetitive during my daily work.

Utils are sorted in:

  • Formatting Utils
    • toCapitalCase(str)String
    • fillNumberUnits(num, units)String
    • createSrcFromBase64(base64Img, format)String
  • Array Utils
    • clearDuplicatedObjects(array, criteria)Array
    • clearDuplicatesSimple(array)Array
  • Math Utils
    • randomBool()boolean
    • random(min, max)number
  • Functions Utils
    • debounce(func, [wait], [options])function
  • Objects Utils
    • deepClone(obj)*
    • sortObjectKeys(obj)Object
    • deepSortObjectKeys(obj)Object
    • deepObjCompare(obj1, obj2)boolean
  • DOM Utils
    • applyStyle(dom, style)
  • Lang Utils
    • isObject(value)boolean
    • toNumber(str)number
  • Bug Solving
    • iosXCodeBugWorkaround(event)

Formatting Utils

Functions

toCapitalCase(str) ⇒ String

Given a String, returns it formatted as Capital Case

Returns: String - A string formatted in Capital Case

| Param | Type | Description | | ----- | ------------------- | --------------------- | | str | String | The string to format. |

Example

const capitalizedTitle = toCapitalCase("something new");
console.log(capitalizedTitle);
// => "Something New"

fillNumberUnits(num, units) ⇒ String

Given a number and an amount of units, returns a string filling with 0 to make the string length match the units amount.

Returns: String - A string containing the formatted number.

| Param | Type | Description | | ----- | ------------------- | ------------------------------------------- | | num | number | The desired number to format | | units | number | The desired length of the formatted number. |

Example

const counter = fillNumberUnits(2, 5);
console.log(counter);
// => "00002"

createSrcFromBase64(base64Img, format) ⇒ String

image string and a desired target format.

Returns: String - A valid src for the img tag.

| Param | Type | Description | | --------- | ------------------- | ------------------------------- | | base64Img | String | The base64 string of the image. | | format | String | The desired target format |

Example

createSrcFromBase64(base64String, "png"))

Array Utils

Functions

clearDuplicatedObjects(array, criteria) ⇒ Array

Given an array of objects and a criteria to detect duplicates, filters the duplicated objects of the array.

Returns: Array - New array without duplicated objects.

| Param | Type | Description | | -------- | ------------------- | --------------------------------------------------------- | | array | Array | Array of objects with duplicated values. | | criteria | String | Key of the objects used as criteria to detect duplicates. |

Example

const originalArray = [{ a: 1 }, { a: 2 }, { a: 1 }, { a: 3 }];
const clearedArray = clearDuplicatedObjects(array, "a");
console.log(clearedArray);
// =>  [{ a: 1 }, { a: 2 }, { a: 3 }]

clearDuplicatesSimple(array) ⇒ Array

Given a simple array, clear the duplicated values and returns a new one.

Note: This will only do a shallow cleaning, this means that arrays made of Objects or other Arrays will not be cleaned. To delete duplicates from an array of objects, check clearDuplicatedObjects

Returns: Array - New array without duplicated values.

See: clearDuplicatedObjects

| Param | Type | Description | | ----- | ------------------ | ------------------------- | | array | Array | Array to clear duplicates |

Math Utils

Functions

randomBool() ⇒ boolean

Generates a random boolean

Returns: boolean - Random boolean

random(min, max) ⇒ number

Generates a random value between a maximum and a minimum points of a range.

Returns: number - Random number between min and maxs

| Param | Type | Description | | ----- | ------------------- | ---------------------- | | min | number | Minimum possible value | | max | number | Maximum possible value |

Functions Utils

debounce(func, [wait], [options]) ⇒ function

Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked. The debounced function comes with a cancel method to cancel delayed func invocations and a flush method to immediately invoke them. Provide options to indicate whether func should be invoked on the leading and/or trailing edge of the wait timeout. The func is invoked with the last arguments provided to the debounced function. Subsequent calls to the debounced function return the result of the last func invocation. Note: If leading and trailing options are true, func is invoked on the trailing edge of the timeout only if the debounced function is invoked more than once during the wait timeout. If wait is 0 and leading is false, func invocation is deferred until to the next tick, similar to setTimeout with a timeout of 0.

Returns: function - Returns the new debounced function.

| Param | Type | Default | Description | | ------------------ | --------------------- | ------------------ | --------------------------------------------------------------------- | | func | function | | The function to debounce. | | [wait] | number | 0 | The number of milliseconds to delay. | | [options] | Object | {} | The options object. | | [options.leading] | boolean | false | Specify invoking on the leading edge of the timeout. | | [options.maxWait] | number | | The maximum time func is allowed to be delayed before it's invoked. | | [options.trailing] | boolean | true | Specify invoking on the trailing edge of the timeout. |

Example

// Avoid costly calculations while the window size is in flux.
window.addEventListener("resize", debounce(calculateLayout, 150));
// Invoke `sendMail` when clicked, debouncing subsequent calls.
window.addEventListener(
  "click",
  debounce(sendMail, 300, {
    leading: true,
    trailing: false
  })
);
// Ensure `batchLog` is invoked once after 1 second of debounced calls.
var debounced = debounce(batchLog, 250, { maxWait: 1000 });
var source = new EventSource("/stream");
webSocket.addEventListener("message", debounced);
// Cancel the trailing debounced invocation.
debounced.cancel();

Objects Utils

Functions

deepClone(obj) ⇒ *

Deeply clones a given value. The difference between using this method and the spread operator method is that the spread operator method doesn't clone the object in depth, but only the first layer of it (shallow copy). So, if we have an array of objects, the object properties are not cloned but referenced to the same memory location as the original, so if we make any changes to the cloned object it would affect the original one. By deeply cloning the object we get a completely new object, not making any references to the original set.

Returns: * - Returns the new cloned object.

| Param | Type | Description | | ----- | --------------- | -------------------------------------------------------- | | obj | * | Given value to clone. Can be any type (Array, Object...) |

sortObjectKeys(obj) ⇒ Object

Given an object, returns a new object (shallow copy) which properties have been sorted by their keys.

Returns: Object - Shallow copy of the given object with its keys sorted.

| Param | Type | Description | | ----- | ------------------- | -------------- | | obj | Object | Object to sort |

Example

const initialObj = { a: 1, c: 2, e: 3, b: 4, d: 5, f: 6 };
sortObjectKeys(initialObj);
// => {a: 1, b: 4, c: 2, d: 5, e: 3, f: 6}

deepSortObjectKeys(obj) ⇒ Object

Given an object, returns a new object (deep copy) which properties have been sorted by their keys.

The difference between this and sortObjectKeys is that this function returns a deep copy, sorting also all the objects contained as property value.

Returns: Object - Deep copy of the given object with its keys sorted.

| Param | Type | Description | | ----- | ------------------- | -------------- | | obj | Object | Object to sort |

Example

const initialObj = { a: 1, c: 2, e: 3, b: 4, d: { b: 1, a: 2 }, f: 6 };
deepSortObjectKeys(initialObj);
// => {a: 1, b: 4, c: 2, d: { a: 2, b: 1 }, e: 3, f: 6}

deepObjCompare(obj1, obj2) ⇒ boolean

Given two objects, checks if both objects are equal by making a deep comparison between them.

Returns: boolean - true if the objects are equal, false if are different.

| Param | Type | Description | | ----- | ------------------- | ------------------------ | | obj1 | Object | First object to compare | | obj2 | Object | Second object to compare |

Example

const obj1 = { a: 1, b: 2, c: 3 };
const obj2 = { a: 1, c: 3, b: 2 };
const obj3 = { a: 4, b: 5, c: 6 };
const obj4 = { a: { b: 1 }, c: 2 };
const obj5 = { a: { b: 2 }, c: 2 };
const obj6 = { a: { b: 1, a: 2 }, c: 2 };
const obj7 = { a: { a: 2, b: 1 }, c: 2 };

deepObjCompare(obj1, obj2);
// => true
deepObjCompare(obj2, obj3);
// => false
deepObjCompare(obj4, obj5);
// => false
deepObjCompare(obj6, obj7);
// => true

DOM Utils

Functions

applyStyle(dom, style)

Given a DOM element and a style object, applies the desired style to the DOM element.

| Param | Type | Description | | ------ | ----------------------------- | ------------------------------------------ | | dom | DOM Element/Node | DOM element to apply the desired style. | | style | Object | Style desired to apply to the DOM element. |

Example

const header = document.querySelector('header')
applyStyle(header, {
 backgroundColor: "#FAFAFA",
 textAlign: "center",
 fontWeight: "bold"
})

Lang Utils

Functions

isObject(value) ⇒ boolean

Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))

Returns: boolean - Returns true if value is an object, else false.

| Param | Type | Description | | ----- | --------------- | ------------------- | | value | * | The value to check. |

Example

isObject({});
// => true
isObject([1, 2, 3]);
// => true
isObject(null);
// => false

toNumber(str) ⇒ number

Parses a string to number, getting rid of all non-numerical values. Accepts both "." and "," as float indicators.

Returns: number - Parsed number from string.

| Param | Type | Description | | ----- | ------------------- | -------------------------------- | | str | String | Given string to parse to number. |

Example

toNumber("0.5");
// => 0.5
toNumber("0,5");
// => 0.5
toNumber("sdfsdf0,5");
// => 0.5
toNumber("sdfsdf0df,5");
// => 0.5
toNumber("sdfsdf0df,5sdf");
// => 0.5

Bug Solving

iosXCodeBugWorkaround

There's a bug in XCode in which the touchscreen won't work properly after the virtual keyboard has hidden in a cordova app.

To solve this, apply this function (only on iOS) on the blur event of the input field.

Note: This bug workaround must be used only on ios apps.

| Param | Type | Description | | ----- | ------------------ | -------------------------------------------------------------------------------------------------------- | | event | Event | The event that triggers the bug workaround. Typically it will be a blur event fired from an input field. |