javascript-utils v1.2.0
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 forvalueto 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 compareobject[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 ensureobjectdoes 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) // trueunixIsWithin(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) // truePromiseUtils
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.