solid-hammers v0.1.0
solid-hammers
A set of JavaScript (ES6) functions and classes for all occasions. Ships with TypeScript support.
This package i still under development and will ship with more functions and classes with time
Table of content (TOC)
Installation
Using npm:
$ npm i solid-hammersUsing yarn:
$ yarn add solid-hammersUsage
// ES6
import * as hammers from 'solid-hammers'
// or
import /* functions */ 'solid-hammers'
// Pick method categories
import * as assert from 'solid-hammers/functions/assert'
import * as invoke from 'solid-hammers/functions/invoke'
// Pick methods.
import { Vector2 } from 'solid-hammers/math/Vector2'
import { isTruthy } from 'solid-hammers/functions/assert/isTruthy'
import { invokeUntil } from 'solid-hammers/functions/invoke/invokeUntil'// ES5
var hammers = require('solid-hammers')
// Pick method categories
var assert = require('solid-hammers/functions/assert')
var invoke = require('solid-hammers/functions/invoke')
var functions = require('solid-hammers/functions')
// Pick methods.
var { Vector2 } = require('solid-hammers/math/Vector2')
var { isTruthy } = require('solid-hammers/functions/assert/isTruthy')
var { invokeUntil } = require('solid-hammers/functions/invoke/invokeUntil')Typescript support
solid-hammers works with TypeScript out of the box since it contains built-in TypeScript declarations.
Math
Vector2
A 2D vector class
average
Returns the average number of a given array of numbers
Syntax
average(numbers)Parameters
numbersarray of real numbers
Return value
returns the average of
numbers(number)
Available since: v0.0.1
Examples
average([20, 5, 5]) // 10
average([20, 5, NaN]) // TypeError
average([20, 5, Infinity]) // TypeError
average([20, 5, undefined]) // TypeError
average([20, 5, null]) // TypeErroravg
see average
Available since: v0.0.1
median
Sorts an array of given real number and return the median
Syntax
median(numbers)Parameters
numbersarray of real numbers
Return value
returns the median of
numbers(number)
Available since: v0.0.1
Examples
median([20, 5, 5]) // 5
median([20, 10, 20]) // 20
median([20, 10, 10, 20]) // 15
median([20, 5, NaN]) // TypeError
median([20, 5, Infinity]) // TypeError
median([20, 5, undefined]) // TypeError
median([20, 5, null]) // TypeErrorFunctions
Assert
falsy
Evaluates if given value is a falsy value.
For TypeScript this function can be used as a type guard that strips any truthy types from the evaluated value
Syntax
falsy(value)Parameters
valuethe value to be checked
Return value
trueifvalueis falsy; otherwise,false
Available since: v0.0.1
Examples
falsy(false) // true
falsy('') // true
falsy(0) // true
falsy(null) // true
falsy(undefined) // true
falsy(123) // false
falsy(true) // false
falsy('someString') // false
falsy([]) // false
falsy({}) // false
falsy(() => {}) // false
// As a type guard
interface SomeInterface {
some: string
other: number
}
type SomeType = number | string | boolean | null
const val1: SomeType | SomeInterface
if(falsy(val1)) {
val1 // val1: false | null
}
const val2: SomeInterface
if(falsy(val2)) {
val2 // val2: never
}isFalsy
For documentation see solid-hammers falsy.
Adapts TypeScript naming convention for type guards.
falsyOr
Evaluates if given value is a falsy value or returns default value.
Syntax
falsyOr(defaultValue, value)Parameters
defaultValuethe value to be returned if evaluation is false
valuethe value to be checked
Return value
defaultValueif evaluation is false; otherwise,value
Available since: v0.0.1
Examples
falsyOr('defaultValue', false) // false
falsyOr('defaultValue', '') // ''
falsyOr('defaultValue', 0) // 0
falsyOr('defaultValue', null) // null
falsyOr('defaultValue', undefined) // undefined
falsyOr('defaultValue', 123) // 'defaultValue'
falsyOr('defaultValue', true) // 'defaultValue'
falsyOr('defaultValue', 'someString') // 'defaultValue'
falsyOr('defaultValue', []) // 'defaultValue'
falsyOr('defaultValue', {}) // 'defaultValue'
falsyOr('defaultValue', () => {}) // 'defaultValue'truthy
Evaluates if given value is a truthy value.
For TypeScript this function can be used as a type guard that strips any falsy types from the evaluated value.
Syntax
truthy(value)Parameters
valuethe value to be checked
Return value
trueifvalueis truthy; otherwise,false
Available since: v0.0.1
Examples
truthy(123) // true
truthy(true) // true
truthy('someString') // true
truthy([]) // true
truthy({}) // true
truthy(() => {}) // true
truthy(false) // false
truthy('') // false
truthy(0) // false
truthy(null) // false
truthy(undefined) // false
// As a type guard
interface SomeInterface {
some: string
other: number
}
type SomeType = number | boolean | null
const val1: SomeType | SomeInterface
if(truthy(val1)) {
val1 // val1: SomeInterface | number | true
}
const val2: null | undefined | false
if(truthy(val2)) {
val2 // val2: never
}isTruthy
For documentation see solid-hammers truthy.
Adapts TypeScript naming convention for type guards.
truthyOr
Evaluates if given value is a truthy value or returns default value.
Syntax
truthyOr(defaultValue, value)Parameters
defaultValuethe value to be returned if evaluation is false
valuethe value to be checked
Return value
defaultValueif evaluation is false; otherwise,value
Available since: v0.0.1
Examples
truthyOr('defaultValue', 123) // 123
truthyOr('defaultValue', true) // true
truthyOr('defaultValue', 'someString') // 'someString'
truthyOr('defaultValue', []) // [] (reference)
truthyOr('defaultValue', {}) // {} (reference)
truthyOr('defaultValue', () => {}) // () => {} (reference)
truthyOr('defaultValue', false) // 'defaultValue'
truthyOr('defaultValue', '') // 'defaultValue'
truthyOr('defaultValue', 0) // 'defaultValue'
truthyOr('defaultValue', null) // 'defaultValue'
truthyOr('defaultValue', undefined) // 'defaultValue'
// Create a default method
const assertTruthyOrReturnEmptyArray = truthyOr.bind(null, [])
Promise.resolve(null).then(assertTruthyOrReturnEmptyArray) // []
Promise.resolve({ data: () => 'data' }).then(assertTruthyOrReturnEmptyArray) // { data: () => 'data' }nullish
Evaluates if given value is a nullish value.
Syntax
nullish(value)Parameters
valuethe value to be checked
Return value
trueifvalueis nullish; otherwise,false
Available since: v0.0.1
Examples
nullish(null) // true
nullish(undefined) // true
nullish(123) // false
nullish(true) // false
nullish('someString') // false
nullish([]) // false
nullish({}) // false
nullish(() => {}) // false
nullish(false) // false
nullish('') // false
nullish(0) // falseisNullish
For documentation see solid-hammers nullish.
Adapts TypeScript naming convention for type guards.
nullishOr
Evaluates if given value is a nullish value or returns default value.
Syntax
nullishOr(defaultValue, value)Parameters
defaultValuethe value to be returned if evaluation is false
valuethe value to be checked
Return value
defaultValueif evaluation is false; otherwise,value
Available since: v0.0.1
Examples
nullishOr('defaultValue', null) // null
nullishOr('defaultValue', undefined) // undefined
nullishOr('defaultValue', 123) // 'defaultValue'
nullishOr('defaultValue', true) // 'defaultValue'
nullishOr('defaultValue', 'someString') // 'defaultValue'
nullishOr('defaultValue', []) // 'defaultValue'
nullishOr('defaultValue', {}) // 'defaultValue'
nullishOr('defaultValue', () => {}) // 'defaultValue'
nullishOr('defaultValue', false) // 'defaultValue'
nullishOr('defaultValue', '') // 'defaultValue'
nullishOr('defaultValue', 0) // 'defaultValue'notNullish
Evaluates if given value is not a nullish value.
Syntax
notNullish(value)Parameters
valuethe value to be checked
Return value
trueifvalueis not nullish; otherwise,false
Available since: v0.0.1
Examples
notNullish(123) // true
notNullish(true) // true
notNullish('someString') // true
notNullish([]) // true
notNullish({}) // true
notNullish(() => {}) // true
notNullish(false) // true
notNullish('') // true
notNullish(0) // true
notNullish(null) // false
notNullish(undefined) // falseisNotNullish
For documentation see solid-hammers notNullish.
Adapts TypeScript naming convention for type guards.
notNullishOr
Evaluates if given value is not a nullish value or returns default value.
Syntax
notNullishOr(defaultValue, value)Parameters
defaultValuethe value to be returned if evaluation is false
valuethe value to be checked
Return value
defaultValueif evaluation is false; otherwise,value
Available since: v0.0.1
Examples
notNullishOr('defaultValue', 123) // 123'
notNullishOr('defaultValue', true) // true
notNullishOr('defaultValue', 'someString') // 'someString'
notNullishOr('defaultValue', []) // [] (reference)
notNullishOr('defaultValue', {}) // {} (reference)
notNullishOr('defaultValue', () => {}) // () => {} (reference)
notNullishOr('defaultValue', false) // false
notNullishOr('defaultValue', '') // ''
notNullishOr('defaultValue', 0) // 0
notNullishOr('defaultValue', null) // 'defaultValue'
notNullishOr('defaultValue', undefined) // 'defaultValue'Invoke
invokeAfter
Creates a function that invokes given fn after it have been called nth or more times. The opposite of
invokeUntil.
Syntax
invokeAfter(nthTime, fn)Parameters
nthTime(real number) the nth number of calls before fn is invoked
fnthe function to be invoked
Return value
new function with nth time call restriction
Available since: v0.0.1
Examples
const log = invokeAfter(3, console.log)
for (let i = 1; i <= 4; i++) {
console.log(i)
log('done on', i)
}
// 1
// 2
// 3
// 'done on 3'
// 4
// 'done on 4'invokeUntil
Creates a function that invokes given fn until it have been called nth times. The opposite of
invokeAfter.
Syntax
invokeUntil(nthTime, fn)Parameters
nthTime(real number) the nth number of calls until fn will no longer be invoked
fnthe function to be invoked
Return value
new function with nth time call restriction
Available since: v0.0.1
Examples
const log = invokeUntil(3, console.log)
for (let i = 1; i <= 4; i++) {
console.log(i)
log('done on', i)
}
// 1
// 'done on 1'
// 2
// 'done on 2'
// 3
// 'done on 3'
// 4invokeOn
Creates a function that invokes given fn on and only on the nth call.
Syntax
invokeOn(nthTime, fn)Parameters
nthTime(real number) the nth number of calls beforefnis invoked
fnthe function to be invoked
Return value
new function with nth time call restriction
Available since: v0.0.1
Examples
const log = invokeOn(3, console.log)
for (let i = 1; i <= 4; i++) {
console.log(i)
log('done on', i)
}
// 1
// 2
// 3
// 'done on 3'
// 4invokeOnce
Creates a function that invokes given fn only the first time when called.
Syntax
invokeOnce(fn)Parameters
fnthe function to be invoked
Return value
new function with one time call restriction
Available since: v0.0.1
Examples
const log = invokeOnce(console.log)
for (let i = 1; i <= 4; i++) {
console.log(i)
log('done on', i)
}
// 1
// 'done on 1'
// 2
// 3
// 4debounce
Creates a debounced function that returns a promise. If the debounced function is invoked multiple times all promises that is created will resolve with the final value or reject
Syntax
debounce(fn, delay)Parameters
fnthe function to be invoked
delaythe debounce delay in milliseconds
Return value
new debounced function
Available since: v0.1.0
Examples
const fetch = debounce(getData, 1000)
const promise = fetch() // Promise 1
const promise2 = fetch() // Promise 2
// delay elapsed
const isSamePromise = promise === promise2 // false, different promises
const response = await promise
const response2 = await promise2
const isSameResponse = response === response2 // true, all promises will resolve with the same valuethrottle
Creates a throttled function. It will cache the response of the first invocation and return it if the throttled function is invoked during throttle duration
Syntax
throttle(fn, duration)Parameters
fnthe function to be invoked
durationthe throttle duration in milliseconds
Return value
new throttled function
Available since: v0.1.0
Examples
const fetch = throttle(getData, 1000)
const promise = fetch() // Promise 1
const promise2 = fetch() // Promise 2
// duration elapsed
const isSamePromise = promise === promise2 // true, promise is cached from first invocation
const response = await promise
const response2 = await promise2
const isSame = response === response2 // true, since the response is cached from the first invocationObject
getValue
Safe property accessor. Functional style for optional chaining.
For TypeScript this method will infer correct return type as long as given path is a readonly array
Syntax
getValue(path, object)Parameters
path((string | number)[]) the path to the property that needs accessed
objectthe object
Return value
the value found at the end of the path; otherwise
undefined
Available since: v0.0.1
Examples
getValue(['some', 'data'], { some: { data: true } }) // true
getValue(['some', 0, 'data'], { some: [{ data: true }] }) // true
getValue(['some', 1, 'data'], { some: [{ data: true }, { data: false }] }) // false
getValue(['some', 'data'], { some: true }) // undefined
getValue(['some'], { some: { data: true } }) // { data: true }
// TypeScript
getValue(['some', 'data'] as const, { some: { data: true } }) // type: true | undefined
getValue(['some'] as const, { some: { data: true } }) // type: { data: true } | undefined
getValue(['a'] as const, { some: { data: true } }) // type: undefined
getValue(['a'] as const, {}) // type: undefinedgetValueOr
Safe property accessor with default value. Functional style for optional chaining and with default value capabilities
Generic TypeScript method
Syntax
getValueOr(defaultValue, path, object)Parameters
defaultValuethe default return value
path((string | number)[]) the path to the property that needs accessed
objectthe object
Return value
the value found at the end of the path; otherwise
defaultValue
Available since: v0.0.1
Examples
getValueOr('defaultValue', ['some', 'data'], { some: { data: true } }) // true
getValueOr('defaultValue', ['some', 'data'], { some: { data: null } }) // null
getValueOr('defaultValue', ['some'], { some: { data: true } }) // { data: true }
getValueOr('defaultValue', ['some', 'data'], { some: { data: undefined } }) // 'defaultValue'
getValueOr('defaultValue', ['some', 'data'], { some: true }) // 'defaultValue'
// TypeScript
getValueOr('defaultValue', ['some', 'data'] as const, { some: { data: true } }) // type: true | 'defaultValue'
getValueOr('defaultValue', ['some'] as const, { some: { data: true } }) // type: { data: true } | 'defaultValue'
getValueOr('defaultValue', ['a'] as const, { some: { data: true } }) // type: 'defaultValue'
getValueOr('defaultValue', ['a'] as const, {}) // type: 'defaultValue'hasDepth
Checks if object has any properties
Generic TypeScript method
Syntax
hasDepth(object)Parameters
objectthe object
Return value
true of
objecthas any properties; otherwise false
Available since: v0.0.1
Examples
hasDepth({ some: { data: true } }) // true
hasDepth({}) // false
hasDepth(null) // false
hasDepth([]) // false
hasDepth([1, 2, 3, 4]) // false
hasDepth([[1], [2]]) // falseArray
enumerate
Creates an enumeration iterator from an array much like
Object.entries
Generic TypeScript method
Syntax
enumerate(array)Parameters
arraythe array to enumerate
Return value
iterator and
toArraymethod that converts the iterator to an array[number,T][]
Available since: v0.1.0
Examples
const iter = enumerate(['a', 'b', 'c'])
for (const [i, value] of iter) {
if (i === 0 || value === 'b') {
// do something
}
}
const array = iter.toArray()range
Creates a rage iterator
Syntax
range(to, options)
range(params, options)Parameters
tothe number to create a range to e.g. 10
paramsan object to specifyfromandtovalue (numbers)
optionsan optional object,options.include: booleanto include the to value in the range, default false
Return value
iterator and
toArraymethod that converts the iterator to an arraynumber[]
Available since: v0.1.0
Examples
const iter = range(5) // [0, 1, 2, 3, 4]
const iter = range(5, { include: true }) // [0, 1, 2, 3, 4, 5]
const iter = range({ to: 5 }) // [0, 1, 2, 3, 4]
const iter = range({ to: 5, from: 2 }) // [2, 3, 4]
const iter = range({ to: 5 }, { include: true }) // [0, 1, 2, 3, 4, 5]
const iter = range({ to: 5, from: 2 }, { include }) // [2, 3, 4, 5]
for (const i of iter) {
if (i === 0) {
// do something
}
}
const array = iter.toArray()2 years ago
4 years ago
4 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago