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

javascript-utils

v1.2.0

Published

A utils library for Javascript.

Downloads

28

Readme

javascript-utils

This npm package is exactly what it sounds like. It's a somewhat random sampling of utility functions for Javascript projects! Feel free to use it in your own projects to make things simpler.

Usage

In package.json:

dependencies: {
    "javascript-utils": "^1",
    ...
}

In whatever file:

const Utils = require('javascript-utils');

Methods

AssertionUtils

These utility methods are typically used as assertions for testing, or in promise chains. They don't return any values, but throw errors instead.

assertEach(asserters)

Asserts that each element of asserters is congruent. This is done by calling assertGeneric on each of asserters's elements.

Since

1.2.0

Arguments

  • asserters (Array): The assertions to make (name, value, validator).

Returns

Nothing.

Throws

An error if any of asserters's elements are not congruent.

Example

Utils.assertionUtils.assertEach([
    ['myInt', 42, 42],
    ['myString', 'foobar', 'foobar'],
    ['positiveNumber', 16, number => number >= 0],
    ['object', { baz: true }, { baz: true }],
    ['qux', undefined, undefined],
]);

assertGeneric(name, value, validator)

Asserts that value is congruent with validator. If validator is a primitive, it is strictly compared to value. If validator is an object, value is expected to be an object. assertSchema is called with value as the object and validator as the schema. If validator is a function, it is called with one argument: value. In this case, validator should return truthy.

Since

1.0.0

Arguments

  • name (String): The name of the value being tested.
  • value (Primitive or Object): The value to be tested.
  • validator (Primitive, Object, or Function): A primitive, object, or function for value to be tested against.

Returns

Nothing.

Throws

An error if value is not congruent with validator.

Example

const validator = input => 'functionInput' === input;
Utils.assertionUtils.assertGeneric('myName', 'functionInput', validator);

Utils.assertionUtils.assertGeneric('myName', 'string', 'string');

const object1 = { bar: 42, foo: { baz: true } };
const object2 = _.cloneDeep(object1);
AssertionUtils.assertGeneric('myName', object1, object2);

assertObjectPropertiesAreAtLeast(object, propertyList = [])

Asserts that for every entry in propertyList, object has a property with that key. This does not check inherited properties.

Since

1.0.0

Arguments

  • object (Object): The object to check.
  • propertyList (Array of Strings): The properties to check for.

Returns

Nothing.

Throws

An error if object doesn't have all required keys.

Example

const object = { foo: 'bar', baz: undefined, qux: 42 };
const propertyList = ['foo', 'baz'];
Utils.assertionUtils.assertObjectPropertiesAreAtLeast(object, propertyList);

assertObjectPropertiesAreExactly(object, propertyList = [])

Asserts that object's keys are exactly equal to propertyList. This does not check inherited properties.

Since

1.0.0

Arguments

  • object (Object): The object to check.
  • propertyList (Array of Strings): The properties to check for.

Returns

Nothing.

Throws

An error if object's keys are not exactly propertyList.

Example

const object = { foo: 'bar', baz: undefined };
const propertyList = ['foo', 'baz'];
Utils.assertionUtils.assertObjectPropertiesAreExactly(object, propertyList);

assertObjectPropertiesAreAtMost(object, propertyList = [])

Asserts that for every object does not have any keys that are not in objectList. This does not check inherited properties.

Since

1.0.0

Arguments

  • object (Object): The object to check.
  • propertyList (Array of Strings): The properties to check for.

Returns

Nothing.

Throws

An error if object has a key that is not in propertyList.

Example

const object = { foo: 'bar' };
const propertyList = ['foo', 'baz'];
Utils.assertionUtils.assertObjectPropertiesAreAtMost(object, propertyList);

assertPropertyIs(object, propertyName, expectedValue)

Asserts that object[propertyName] === expectedValue.

Since

1.0.0

Arguments

  • object (Object): The object to check on.
  • propertyName (String): The key to check.
  • expectedValue (Any): The value to compare object[propertyName] against.

Returns

Nothing.

Throws

An error if object[propertyName] !== expectedValue.

Example

const object = { foo: 'bar' };
Utils.assertionUtils.assertPropertyIs(object, 'foo', 'bar');

assertSchema(object, schema, { strict = true } = {})

For each property on schema, asserts that the same property on object is congruent. This is done by calling assertGeneric on each of schema's properties. If strict is true or not provided, this also ensures that object does not have any additional properties.

Since

1.0.0

Arguments

  • object (Object): The object to check.
  • schema (Object): An object of validators.
  • strict (Boolean): Whether or not to ensure object does not have any additional properties.

Returns

Nothing.

Throws

An error if any of object's properties are not congruent with their validators.

Example

const object = {
    myInt: 42,
    myString: 'foobar',
    positiveNumber: 16
    object: { baz: true },
    qux: undefined,
};

const schema = {
    myInt: 42,
    myString: 'foobar',
    positiveNumber: number => number >= 0,
    object: { baz: true },
    qux: undefined,
};

Utils.assertionUtils.assertSchema(object, schema);

DateTimeUtils

These utility methods are convenient when dealing with dates. Most of them work with native Dates, or any String or Number that Moment.js accepts.

createTimestampsFromDates(dates)

For each date in dates, converts it to a unix timestamp (seconds, not ms).

Since

1.0.0

Arguments

  • dates (Object or Array of Dates, Strings, Numbers, or Moments): The dates to convert.

Returns

(Object) The unix timestamps, using the same keys as dates

Example

const startDate = new Date(2014, 1, 14, 10, 30);
const endDate = new Date();

const { startDate: startDateTimestamp, endDate: endDateTimestamp } =
    Utils.dateTimeUtils.createTimestampsFromDates({ startDate, endDate });

isWithin(expectedDate, amount, unit)(actualDate)

Creates a function that checks whether actualDate is within some period of expectedDate.

Since

1.0.0

Arguments

  • expectedDate (Date, String, Number, or Moment): The target date.
  • amount (Number): The number of units to allow.
  • unit (String): The time unit to use ('ms', 'seconds', 'day', etc.).
  • actualDate (Date, String, Number, or Moment): The date to check.

Returns

(Boolean) Whether or not actualDate was within the range.

Example

const expectedDate = new Date(2014, 1, 14, 10, 30);

const dateValidator = Utils.dateTimeUtils.isWithin(expectedDate, 30, 'minutes');

const actualDate = new Date(2014, 1, 14, 10, 45);

dateValidator(actualDate) // true

unixIsWithin(expectedDate, amount, unit)(actualDate)

Creates a function that checks whether actualDate is within some period of expectedDate. The same as isWithin, where actualDate is expected to be a unix timestamp (seconds, not ms)

Since

1.0.0

Arguments

  • expectedDate (Date, String, Number, or Moment): The target date.
  • amount (Number): The number of units to allow.
  • unit (String): The time unit to use ('ms', 'seconds', 'day', etc.).
  • actualDate (String or Number): The unix timestamp to check.

Returns

(Function) A function that returns whether or not actualDate was within the range.

Example

const expectedDate = new Date(2014, 1, 14, 10, 30);

const dateValidator = Utils.dateTimeUtils.isWithin(expectedDate, 30, 'minutes');

const actualDate = '1392391200';

dateValidator(actualDate) // true

PromiseUtils

These utility methods are for handling promises and sometimes doing weird things with them.

expectPromiseRejection(promise)

Creates a promise that resolves if and when the argument promise rejects, and rejects if and when the argument promise resolves. In short, it inverts a promise.

Since

1.1.0

Arguments

  • promise (Promise): The promise to invert.

Returns

(Promise) A promise that resolves if and when the argument promise rejects, and rejects if and when the argument promise resolves

WebRequestUtils

These utility methods are designed to be useful when mocking web requests for testing purposes.

returnRequestAsResponse(path, options = {})

Creates an object of the path and options arguments. Even if options is not provided, this function generates an options property on the response object.

Since

1.0.0

Arguments

  • path (String): The path of a web request.
  • options (Object): The options for a web request.

Returns

(Promise) A promise that resolves to an object containing path and options.

returnRequestAsResponseBody(path, options = {})

Creates an object containing one property: body. The body property is a string that can be deserialized to yield an object with path and options as properties. Even if options is not provided, this function generates an options property on body.

Since

1.0.0

Arguments

  • path (String): The path of a web request.
  • options (Object): The options for a web request.

Returns

(Promise) A promise that resolves to the described object.

returnSomething(whatToReturn)

Creates a function that returns a promise that always resolves to whatToReturn.

Since

1.0.0

Arguments

  • whatToReturn (Any): What the promise should resolve to.

Returns

(Function) A function that returns a promise that always resolves to whatToReturn.