0.1.0 • Published 10 months ago

solid-hammers v0.1.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

solid-hammers

CI Status GitHub license npm version

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)

  1. Installation
  2. Usage as a module
    1. TypeScript support
  3. Math
    1. Vector2
    2. average
    3. avg
    4. median
  4. Functions
    1. Assert
      1. falsy
      2. isFalsy
      3. falsyOr
      4. truthy
      5. isTruthy
      6. truthyOr
      7. nullish
      8. isNullish
      9. nullishOr
      10. notNullish
      11. isNotNullish
      12. notNullishOr
    2. Invoke
      1. invokeAfter
      2. invokeBefore
      3. invokeUntil
      4. invokeOn
      5. invokeOnce
      6. debounce
      7. throttle
    3. Object
      1. getValue
      2. getValueOr
      3. hasDepth
    4. Array
      1. enumerate

Installation

Using npm:

$ npm i solid-hammers

Using yarn:

$ yarn add solid-hammers

Usage

// 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

numbers array 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]) // TypeError

avg

see average

Available since: v0.0.1

median

Sorts an array of given real number and return the median

Syntax

median(numbers)

Parameters

numbers array 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]) // TypeError

Functions

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

value the value to be checked

Return value

true if value is 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

defaultValue the value to be returned if evaluation is false
value the value to be checked

Return value

defaultValue if 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

value the value to be checked

Return value

true if value is 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

defaultValue the value to be returned if evaluation is false
value the value to be checked

Return value

defaultValue if 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

value the value to be checked

Return value

true if value is 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) // false

isNullish

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

defaultValue the value to be returned if evaluation is false
value the value to be checked

Return value

defaultValue if 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

value the value to be checked

Return value

true if value is 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) // false

isNotNullish

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

defaultValue the value to be returned if evaluation is false
value the value to be checked

Return value

defaultValue if 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
fn the 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
fn the 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'

// 4

invokeOn

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 before fn is invoked
fn the 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'

// 4

invokeOnce

Creates a function that invokes given fn only the first time when called.

Syntax

invokeOnce(fn)

Parameters

fn the 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

// 4

debounce

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

fn the function to be invoked
delay the 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 value

throttle

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

fn the function to be invoked
duration the 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 invocation

Object

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
object the 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: undefined

getValueOr

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

defaultValue the default return value
path ((string | number)[]) the path to the property that needs accessed
object the 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

object the object

Return value

true of object has 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]]) // false

Array

enumerate

Creates an enumeration iterator from an array much like Object.entries

Generic TypeScript method

Syntax

enumerate(array)

Parameters

array the array to enumerate

Return value

iterator and toArray method 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

to the number to create a range to e.g. 10
params an object to specify from and to value (numbers)
options an optional object, options.include: boolean to include the to value in the range, default false

Return value

iterator and toArray method that converts the iterator to an array number[]
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()
0.1.0

10 months ago

0.0.1

2 years ago

0.0.2

2 years ago

1.3.0

3 years ago

1.2.0

3 years ago

1.1.0

3 years ago

1.0.13

3 years ago

1.0.2

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.11

3 years ago

1.0.10

3 years ago

1.0.12

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago