vanilla-commons

Lightweight common vanilla utilities for the modern web development

Usage no npm install needed!

<script type="module">
  import vanillaCommons from 'https://cdn.skypack.dev/vanilla-commons';
</script>

README

vanilla-commons

Lightweight common vanilla utilities for the modern web development

npm Travis Coveralls David gzip size

Table of Contents

Install

This project uses node and npm. Go check them out if you don't have them locally installed.

$ npm install --save vanilla-commons

The UMD build is also available on jsdelivr:

<script src="https://cdn.jsdelivr.net/npm/vanilla-commons/dist/vanilla-commons.umd.min.js"></script>

You can find the library on window.commons.

Usage

import {
  addMinutes,
  addHours,
  addDays,
  addMonths,
  addYears,
  formatDate,
  pipe
} from 'vanilla-commons'

const date = new Date('December 17, 1995 03:24:00')
const format = '{DD}/{MM}/{YYYY} {HH}:{mm}:{ss}:{ms}'

const finalDate = pipe(
  addMinutes(1),
  addHours(9),
  addDays(7),
  addMonths(-9),
  addYears(-2),
  formatDate(format)
)(date)
// '24/03/1993 12:25:00:00'

Array Commons

flattenArray(arr)

Flatten nested arrays.

Parameters

  • arr Array Nested array.

Returns

Array flattened.

Examples

import {flattenArray} from 'vanilla-commons'

flattenArray([[1], [2, [3, 4]]])
// [1, 2, 3, 4]

Date Commons

addDays(days, date)

Add days to a Date.

Parameters

  • days Number of days to add.
  • date Date to be modified.

Returns

Date with the days added.

Examples

import {addDays} from 'vanilla-commons'

addDays(6, new Date('December 17, 1995 03:24:00'))
// Sat, 23 Dec 1995 03:24:00

addDays(-6, new Date('December 17, 1995 03:24:00'))
// Mon, 11 Dec 1995 03:24:00

addDays(6)(new Date('December 17, 1995 03:24:00'))
// Sat, 23 Dec 1995 03:24:00

addHours(hours, date)

Add hours to a Date.

Parameters

  • hours Number of hours to add.
  • date Date to be modified.

Returns

Date with the hours added.

Examples

import {addHours} from 'vanilla-commons'

addHours(6, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:00

addHours(-6, new Date('December 17, 1995 03:24:00'))
// Fri, 16 Dec 1995 21:24:00

addHours(6)(new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:00

addMilliseconds(milliseconds, date)

Add milliseconds to a Date.

Parameters

  • milliseconds Number Number of milliseconds to add.
  • date Date Date to be modified.

Returns

Date with the milliseconds added.

Examples

import {addMilliseconds} from 'vanilla-commons'

addMilliseconds(1000, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:01

addMilliseconds(-1000, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:23:59

addMilliseconds(1000)(new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:01

addMinutes(minutes, date)

Add minutes to a Date.

Parameters

  • minutes Number of minutes to add.
  • date Date to be modified.

Returns

Date with the minutes added.

Examples

import {addMinutes} from 'vanilla-commons'

addMinutes(6, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:06

addMinutes(-6, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:23:54

addMinutes(6)(new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:24:06

addMonths(months, date)

Add months to a Date.

Parameters

  • months Number of months to add.
  • date Date to be modified.

Returns

Date with the months added.

Examples

import {addMonths} from 'vanilla-commons'

addMonths(6, new Date('December 17, 1995 03:24:00'))
// Mon, 17 Jun 1996 09:24:00

addMonths(-6, new Date('December 17, 1995 03:24:00'))
// Sat, 17 Jun 1995 09:24:00

addMonths(6)(new Date('December 17, 1995 03:24:00'))
// Mon, 17 Jun 1996 09:24:00

addSeconds(seconds, date)

Add seconds to a Date.

Parameters

  • seconds Number of seconds to add.
  • date Date to be modified.

Returns

Date with the seconds added.

Examples

import {addSeconds} from 'vanilla-commons'

addSeconds(6, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:30:00

addSeconds(-6, new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:18:00

addSeconds(6)(new Date('December 17, 1995 03:24:00'))
// Sun, 17 Dec 1995 09:30:00

addWeeks(weeks, date)

Add weeks to a Date.

Parameters

  • weeks Number of weeks to add.
  • date Date to be modified.

Returns

Date with the weeks added.

Examples

import {addWeeks} from 'vanilla-commons'

addWeeks(1, new Date('December 17, 1995 03:24:00'))
// Sun, 24 Dec 1995 09:24:00

addWeeks(-1, new Date('December 17, 1995 03:24:00'))
// Sun, 10 Dec 1995 09:24:00

addWeeks(6)(new Date('December 17, 1995 03:24:00'))
// Sun, 24 Dec 1995 09:24:00

addYears(years, date)

Add years to a Date.

Parameters

  • years Number of years to add.
  • date Date to be modified.

Returns

Date with the years added.

Examples

import {addYears} from 'vanilla-commons'

addYears(1, new Date('December 17, 1995 03:24:00'))
// Tue, 17 Dec 1996 09:24:00

addYears(-1, new Date('December 17, 1995 03:24:00'))
// Sat, 17 Dec 1994 09:24:00

addYears(1)(new Date('December 17, 1995 03:24:00'))
// Tue, 17 Dec 1996 09:24:00

diffDate(firstDate, secondDate)

Calculate the diff of two Date objects.

Parameters

  • firstDate Date to be compared.
  • secondDate Date to be compared.

Returns

Date with the years added.

Examples

import {diffDate} from 'vanilla-commons'

diffDate(
  new Date('December 17, 1995 03:24:00'),
  new Date('December 17, 1996 03:25:00')
)
// {
//   milliseconds: 31622460000,
//   seconds: 31622460,
//   minutes: 527041,
//   hours: 8784.02,
//   days: 366,
//   weeks: 52.29,
//   months: 12.2,
//   years: 1
// }

formatDate(format, date)

Format a date given a expected format. Use the following patterns inside your format:

  • {YYYY}: full year; 2017
  • {YY}: short year; 17
  • {MM}: month; 04
  • {DD}: day; 01
  • {HH}: hours; 06 (24h)
  • {mm}: minutes; 59
  • {ss}: seconds; 09
  • {ms}: milliseconds; 10

Parameters

  • format string expected format of the date.
  • date Date to be compared.

Returns

string formatted date.

Examples

import {formatDate} from 'vanilla-commons'

formatDate(
  '{DD}/{MM}/{YYYY} {HH}:{mm}:{ss}:{ms}',
  new Date('December 17, 1995 03:24:00')
)
// '17/12/1995 03:24:00:00'

isValidDate(format, dateStr)

Checks the validity of a given date string. Use the following patterns inside your format:

  • {YYYY}: full year; 2017
  • {YY}: short year; 17
  • {MM}: month; 04
  • {DD}: day; 01
  • {HH}: hours; 06 (24h)
  • {mm}: minutes; 59
  • {ss}: seconds; 09
  • {ms}: milliseconds; 10

Parameters

  • format string expected format of the date.
  • dateStr string date string to be tested.

Returns

Boolean true if the date is valid.

Examples

import {isValidDate} from 'vanilla-commons'

isValidDate('{DD}/{MM}/{YYYY} {HH}:{mm}:{ss}:{ms}', '17/12/1995 03:24:00:00')
// true

isValidDate('{DD}/{MM}/{YYYY} {HH}:{mm}:{ss}:{ms}', '29/02/1995 03:24:00:00')
// false

parseDate(format, dateStr)

Parse a date string to a date object given a format. Use the following patterns inside your format:

  • {YYYY}: full year; 2017
  • {YY}: short year; 17
  • {MM}: month; 04
  • {DD}: day; 01
  • {HH}: hours; 06 (24h)
  • {mm}: minutes; 59
  • {ss}: seconds; 09
  • {ms}: milliseconds; 10

Parameters

  • format string the format of the date string.
  • dateStr string date string to be parsed.

Returns

Date parsed date.

Examples

import {parseDate} from 'vanilla-commons'

parseDate('{DD}/{MM}/{YYYY} {HH}:{mm}:{ss}:{ms}', '17/12/1995 03:24:00:00')
// Sun, 17 Dec 1995 03:24:00

Element Commons

addClass(newClass, element)

Add a class to a DOM Element.

Parameters

  • newClass (Array | string) Array or string of class to add to a DOM Element.
  • element Element Element to apply the changes.

Returns

Element in which the changes were made.

Examples

import {addClass} from 'vanilla-commons'

const element = document.querySelector('.element')
addClass('hey')(element)
// <div class="element hey"></div>

addClass(['there', 'man'], element)
// <div class="element hey there man"></div>

clearEvents(element)

Remove all the event listeners of a element and its children.

Parameters

  • element Element Element that will have its events removed.

Returns

Element element that the events were removed.

Examples

// See the tests for better examples https://github.com/gugutz/vanilla-commons/blob/master/test/element/clear-events.test.js
import {clearEvents} from 'vanilla-commons'

const element = document.querySelector('.element')
clearEvents(element)

createElement(selector?, props?, children?)

Create a DOM element.

Parameters

Returns

Element created.

Examples

// See the tests for better examples https://github.com/gugutz/vanilla-commons/blob/master/test/element/create-element.test.js
import {createElement} from 'vanilla-commons'

createElement()
// <div></div>

createElement('input#id.class[type=text][required]')
// <input id="id" class="class" type="text" disabled required/>

createElement('div', {
  data: {
    ref: 'hey',
    error: 'bad'
  }
})
// <div data-ref="hey" data-error="bad"></div>

createElement('p', {
  className: 'hey there man'
})
// <p class="hey there man"></p>

createElement('p', {
  onclick: function() {
    console.log('clicked')
  }
})
// It's easy to work with events!

createElement('div', [
  createElement('input[type=text]'),
  'hey',
  createElement('img[src=coolimage.jpg]')
])
// <div>
//   <input type=""/>
//   hey
//   <img src="coolimage.jpg"/>
// </div>

getParents(element)

Get all the parents of a given element.

Parameters

  • element Element Reference element.

Returns

Array the parents of the element, including the body.

Examples

// See the tests for better examples https://github.com/gugutz/vanilla-commons/blob/master/test/element/get-parents.test.js
import {getParents} from 'vanilla-commons'

const element = document.querySelector('.element')
getParents(element)

hasClass(classToCheck, element)

Check if a DOM Element has the specified class.

Parameters

  • classToCheck (Array | string) Array or string of class to check the existence in a DOM Element.
  • element Element Element to apply the changes.

Returns

Element to check if has the specified class.

Examples

import {hasClass} from 'vanilla-commons'

const element = document.createElement('div')
element.className = 'hey there'

hasClass('hey')(element)
// true

hasClass('hey', element)
// true

hasClass('man', element)
// false

hasClass(['hey', 'there'], element)
// true

hasClass(['hey', 'man'], element)
// false

hideElement(elementToHide)

Hide a Element from the DOM.

Parameters

  • elementToHide (Array | Element) Array of elements or element to hide.

Returns

(Array | Element) element or array of elements that were hidden.

Examples

import {hideElement} from 'vanilla-commons'

const element = document.createElement('div')
element.style.display
// block

hideElement(element)
element.style.display
// none
import {hideElement} from 'vanilla-commons'

const element1 = document.createElement('div')
element1.style.display
// block

const element2 = document.createElement('div')
element2.style.display
// block

hideElement([element1, element2])

element1.style.display
// none

element2.style.display
// none

insertElementAfter(referenceElement, newElement)

Insert a element after a reference element.

Parameters

  • referenceElement Element Reference element.
  • newElement Element Element to be inserted.

Returns

Element that were inserted.

Examples

import {insertElementAfter} from 'vanilla-commons'

insertElementAfter(referenceElement, newElement)

insertElementBefore(referenceElement, newElement)

Insert a element before a reference element.

Parameters

  • referenceElement Element Reference element.
  • newElement Element Element to be inserted.

Returns

Element that were inserted.

Examples

import {insertElementBefore} from 'vanilla-commons'

insertElementBefore(referenceElement, newElement)

killElement(elementToKill)

Kill a Element from the DOM.

Parameters

  • elementToKill (Array | Element) Array of elements or element to kill.

Examples

import {killElement} from 'vanilla-commons'

killElement(element)

killElement([element1, element2])

removeClass(classToRemove, element)

Remove a class of a DOM Element.

Parameters

  • classToRemove (Array | string) Array or string of class to remove of a DOM Element.
  • element Element Element to apply the changes.

Returns

Element that the had the class removed.

Examples

import {removeClass} from 'vanilla-commons'

removeClass('hey')(element)

removeClass('hey', element)

removeClass(['hey', 'there'], element)

replaceElement(originalElement, newElement)

Replace a DOM element with another element.

Parameters

  • originalElement Element Element to be replaced.
  • newElement Element New element to replace the old one.

Returns

Element element that replaced the old one.

Examples

import {replaceElement} from 'vanilla-commons'

replaceElement(originalElement, newElement)

showElement(elementToShow)

Show a hidden Element from the DOM.

Parameters

  • elementToShow (Array | Element) Array of elements or element to hide.

Returns

(Array | Element) element or array of elements that were showed.

Examples

import {showElement} from 'vanilla-commons'

showElement(element)

showElement([element1, element2])

toggleClass(classToToggle, element)

Toggle a class from a DOM Element.

Parameters

  • classToToggle (Array | string) Array or string of class to toggle a DOM Element.
  • element Element to apply the changes.

Returns

Element that the changes were made.

Examples

import {toggleClass} from 'vanilla-commons'

toggleClass('hey')(element)

toggleClass('hey', element)

toggleClass(['hey', 'there'], element)

Function Commons

compose(fn[, fn1, ..., fnN])

Performs right-to-left function composition.

Parameters

  • fn...fnN Function functions to be composed.

Returns

Examples

import {curry, compose} from 'vanilla-commons'

const add = curry((a, b) => a + b)

const multiply = curry((a, b) => a * b)

const composedFunction = compose(add(5), multiply(4), add(3))
composedFunction(2)
// (((2 + 3) * 4) + 5) = 25

curry(fn)

Returns a curried equivalent of the provided function

Parameters

Returns

Examples

import {curry} from 'vanilla-commons'

const addFourNumbers = (a, b, c, d) => a + b + c + d

const curriedAddFourNumbers = curry(addFourNumbers)
curriedAddFourNumbers(1, 2)(3)(4)
// 10

curriedAddFourNumbers(1, 2)(3, 4)
// 10

curriedAddFourNumbers(1)(2)(3)(4)
// 10

curriedAddFourNumbers(1, 2, 3)(4)
// 10

pipe(fn[, fn1, ..., fnN])

Performs left-to-right function composition.

Parameters

  • fn...fnN Function functions to be piped.

Returns

Examples

import {curry, pipe} from 'vanilla-commons'

const add = curry((a, b) => a + b)

const multiply = curry((a, b) => a * b)

const pipedFunction = pipe(add(5), multiply(4), add(3))
pipedFunction(2)
// (((2 + 5) * 4) + 3) = 31

throttle(limit, fn)

Creates a function that will call fn at most once every wait milliseconds.

Parameters

  • limit Number time in milliseconds to wait.
  • fn Function function to be executed.

Returns

Examples

import {throttle} from 'vanilla-commons'

window.addEventListener('scroll', throttle(100, e => {
  console.log(e)
}))

Number Commons

round(num)

Round a number to two decimal places.

Parameters

  • num Number number to be rounded.

Returns

Number rounded number.

Examples

import {round} from 'vanilla-commons'

round(3.141592)
// 3.14

round(-27.817987)
// -27.82

Object Commons

mapKeys(fn, obj)

Map over the keys of a object.

Parameters

  • fn Function function that will be invoked per iteration.
  • obj Object object to be mapped.

Returns

Object mapped object.

Examples

import {mapKeys} from 'vanilla-commons'

mapKeys(function(key) {
  return key + 'hey'
}, {
  captain: 'picard',
  firstOfficer: 'riker'
})
// {
//   captainhey: 'picard',
//   firstOfficerhey: 'riker'
// }

mapValues(fn, obj)

Map over the values of a object.

Parameters

  • fn Function function that will be invoked per iteration.
  • obj Object object to be mapped.

Returns

Object mapped object.

Examples

import {mapValues} from 'vanilla-commons'

mapValues(function(value) {
  return value + 'hey'
}, {
  captain: 'picard',
  firstOfficer: 'riker'
})
// {
//   captain: 'picardhey',
//   firstOfficer: 'rikerhey'
// }

String Commons

capitalize(str)

Converts the first character of string to upper case.

Parameters

  • str string string to be capitalized.

Returns

string capitalized string.

Examples

import {capitalize} from 'vanilla-commons'

capitalize('vanilla')
// Vanilla

cleanUpString(str)

Removes the all line breaks in the entire string and also the white spaces from the both ends of the string.

Parameters

  • str string string to be cleaned.

Returns

string clean string.

Examples

import {cleanUpString} from 'vanilla-commons'

cleanUpString('\n \n\r \r\n')
// ''

cleanUpString('\n \n\r hjhj ')
// 'hjhj'

Prior Art

Vanilla Commons is fully inspired by these projects:

Contributing

See the contributing file.

License

MIT License © Gustavo P Borges