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

ksjs

v1.8.1

Published

A bunch of random JavaScript functions

Downloads

18

Readme

ksjs

This repo contains a bunch of plain JavaScript functions that come in handy while working on various projects. They are mostly provided as ES modules, but a subset of them are also offered as CommonJS modules so they can easily be used in an older node.js environment.

Install

From the command line, run:

npm install ksjs

or

yarn add ksjs

ES Modules

Preferred: For any of the modules, you can import functions like so:

import {example1, example2} from 'ksjs/example.mjs'
// Depending on your project, ES modules are available in
// files with the .js extension, too. For example:
// import {example1, example2} from 'ksjs/example.js'

example1('foo');
example2('bar');

Not recommended: If your bundler supports ES module tree shaking, you might be able to import functions from various files like so (for Webpack, you might need to configure it to treat bamfjs as ES6+):

import {$, debounce, deepCopy} from 'bamfjs';

CommonJS Modules

The following modules & their corresponding functions can be used in a node.js environment:

  • array
  • color
  • math
  • object
  • promise
  • string
  • timer
  • url

Preferred: You can require them from their respective files with the .cjs extension, like so:

const {example1} = require('ksjs/example.cjs');

example1('foo');

or like so:

const examples = require('ksjs/example.cjs');

examples.example1('foo');

Otherwise: You could require them from the cjs directory, like so (Note the ".js" extension here):

const {example1} = require('ksjs/cjs/example.js');

example1('foo');

or like so:

const examples = require('ksjs/cjs/example.js');

examples.example1('foo');


Modules

  • ajax
  • array
  • color
  • cookie
  • dom
  • event
  • form
  • jsonp
  • math
  • object
  • promise
  • selection
  • storage
  • string
  • timer
  • url

ajax

ESM Import Example:

import {getJSON} from 'ksjs';

// or:
import {getJSON} from 'ksjs/ajax.js';
// or:
import {getJSON} from 'ksjs/ajax.mjs';

ajax([url], options) ⇒ Promise

Low-level ajax request

Returns: Promise - A resolved or rejected Promise from the server

| Param | Type | Default | Description | | --- | --- | --- | --- | | [url] | string | location.href | The URL of the resource | | options | object | | | | [options.dataType] | string | | One of 'json', 'html', 'xml', 'form', 'formData'. Used for setting the Content-Type request header (e.g. multipart/form-data when 'formData) and processing the response (e.g. calling JSON.parse() on a string response when 'json'); | | [options.data] | <code>Object</code> \| <code>string</code> | | Data to send along with the request. If it's a GET request and options.datais an object, the object is converted to a query string and appended to the URL. | | [options.method] | <code>string</code> | <code>&quot;GET&quot;</code> | One of 'GET', 'POST', etc. | | [options.cache] | <code>boolean</code> | <code>true</code> | If set tofalse, will not let server use cached response | | [options.memcache] | <code>boolean</code> | <code>false</code> | If set to true, and a previous request sent to the same url was successful, will circumvent request and use the previous response | | [options.headers] | <code>Object</code> | <code>{}</code> | **Advanced**: Additional headers to send with the request. If headers such as 'Accept', 'Content-Type', 'Cache-Control', 'X-Requested-With', etc., are set here, they will override their respective headers set automatically based on other options such as options.dataTypeandoptions.cache`. | | [options.form] | HTMLFormElement | | An optional form element |

getJSON([url], [options]) ⇒ Promise

Send a GET request and return parsed JSON response from the resolved Promise

Returns: Promise - A resolved or rejected Promise from the server

See: ajax

| Param | Type | Default | Description | | --- | --- | --- | --- | | [url] | string | location.href | The URL of the resource | | [options] | Object | {} | See ajax for details |

postJSON([url], [options]) ⇒ Promise

Send a POST request and return parsed JSON response from the resolved Promise

Returns: Promise - A resolved or rejected Promise from the server

See: ajax

| Param | Type | Default | Description | | --- | --- | --- | --- | | [url] | string | location.href | The URL of the resource | | [options] | Object | {} | See ajax for details |

postFormData([url], [options]) ⇒ Promise

Send a POST request with FormData derived from form element provided by options.form

Returns: Promise - A resolved or rejected Promise from the server

See: ajax

| Param | Type | Default | Description | | --- | --- | --- | --- | | [url] | string | location.href | The URL of the resource | | [options] | Object | {} | See ajax for details |

fetchHTML(url, selector) ⇒ Promise

Fetch an HTML document and return the html string (or a subset of it) from the resolved Promise

Returns: Promise - A resolved or rejected Promise, resolving to an HTML string

| Param | Type | Description | | --- | --- | --- | | url | string | The URL of the resource to fetch | | selector | string | A selector specifying the html content in the resource to return |

array

ESM Import Example:

import {isArray} from 'ksjs';

// or:
import {isArray} from 'ksjs/array.mjs';
// or:
import {isArray} from 'ksjs/array.js';

CommonJS Require Example:

const {isArray} = require('ksjs/array.cjs');
// or:
const {isArray} = require('ksjs/cjs/array.js');

isArray(arr) ⇒ boolean

Determine whether "arr" is a true array

Returns: boolean - true if arr is array, false if not

| Param | Type | Description | | --- | --- | --- | | arr | array | item to determine whether it's an array |

Example

import {isArray} from 'ksjs/array.js';

if (isArray(window.foo)) {
  window.foo.push('bar');
}

inArray(el, arr) ⇒ boolean

Determine whether item "el" is in array "arr"

Returns: boolean - Boolean (true if el is in array, false if not)

| Param | Type | Description | | --- | --- | --- | | el | any | An item to test against the array | | arr | array | The array to test against |

objectToArray(obj) ⇒ array

Convert an object to an array of objects with name and value properties

Returns: array - An array of objects with name and value properties

| Param | Type | Description | | --- | --- | --- | | obj | object | The object to convert |

Example

import {objectToArray} from 'ksjs/array.js';

const obj = {
  foo: 'bar',
  baz: 'qux'
};

const arr = objectToArray(obj);
 // arr = [
//   {name: 'foo', value: 'bar'},
//   {name: 'baz', value: 'qux'}
// ];

makeArray(value, [delimiter], [wrapObject]) ⇒ array

Return an array based on the given value: a) Strings are split by a delimiter (defaults to /\s+/). b) Plain objects are converted to an array of objects with name and value properties. b2) …unless wrapObject is true in which case they are just wrapped in an array c) Undefined and null are returned as an empty array. d) Arrays are returned as is. e) Anything else is wrapped in an array.

Returns: array - The value converted to an array

| Param | Type | Default | Description | | --- | --- | --- | --- | | value | any | | The value to convert to an array | | [delimiter] | string | RegExp | "= /\s+/" | A string or regular expression to use for splitting a string into an array (defaults to /\s+/) | | [wrapObject] | Boolean | | Whether to simply wrap an object in an array (true) or convert to array of objects with name/value properties |

Example

import {makeArray} from 'ksjs/array.js';
const foo = makeArray('one two three');
// foo is now ['one', 'two', 'three']

const bar = makeArray('one,two,three', ',');
// bar is now ['one', 'two', 'three']

const baz = makeArray(['one', 'two', 'three']);
// baz is still ['one', 'two', 'three']

const quz = makeArray({foo: 'bar'});
// quz is now [{name: 'foo': value: 'bar'}]

const quuz = makeArray(null);
// quuz is now []

randomItem(arr) ⇒ any

Return a random item from the provided array

Returns: any - A random element from the provided array

| Param | Type | Description | | --- | --- | --- | | arr | array | An array of elements |

pluck(arr, prop) ⇒ array

Take an array of objects and a property and return an array of values of that property

Returns: array - Array of values of the property (if the value is undefined, returns null instead)

| Param | Type | Description | | --- | --- | --- | | arr | array | Array from which to pluck | | prop | string | Property to pluck |

Example

import {pluck} from 'ksjs/array.js';

let family = [
  {
    id: 'dad',
    name: 'Karl'
  },
  {
    id: 'mom',
    name: 'Sara',
    color: 'blue'
  },
  {
    id: 'son',
    name: 'Ben',
    color: 'green'
  },
  {
    id: 'daughter',
    name: 'Lucy'
  }
];

let names = pluck(family, 'name');
let ids = pluck(family, 'id');
let colors = pluck(family, 'color');

console.log(names);
// Logs: ['Karl', 'Sara', 'Ben', 'Lucy']

console.log(ids);
// Logs: ['dad', 'mom', 'son', 'daughter']

console.log(colors);
// Logs: [null, 'blue', 'green', null]

shuffle(els) ⇒ array

Fisher-Yates (aka Knuth) shuffle. Takes an array of elements and returns the same array, but with its elements shuffled

Returns: array - The array passed to arr, shuffled

See: knuth-shuffle

| Param | Type | Description | | --- | --- | --- | | els | array | Array to be shuffled |

merge(...arrays) ⇒ array

Merge two or more arrays into a single, new array.

Returns: array - A new merged array

| Param | Type | Description | | --- | --- | --- | | ...arrays | array | 2 or more arrays to collapse |

~~collapse()~~

Deprecated

See: merge instead

intersect(array1, array2, [prop]) ⇒ array

Return a subset of array1, only including elements from array2 that are also in array1.

  • If prop is provided, only that property of an element needs to match for the two arrays to be considered intersecting at that element

Returns: array - A new filtered array

| Param | Type | Description | | --- | --- | --- | | array1 | array | First array | | array2 | array | Second array | | [prop] | any | Optional property to compare in each element of the array |

Example

const array1 = [{name: 'Foo', id: 'a'}, {name: 'Bar', id: 'b'}];
const array2 = [{name: 'Foo', id: 'z'}, {name: 'Zippy', id: 'b'}];

console.log(intersect(array1, array2, 'name'));
// Logs [{name: 'Foo', id: 'a'}]

console.log(intersect(array1, array2, 'id'));
// Logs [{name: 'Bar', id: 'b'}]

unique(arr, [prop]) ⇒ array

Take an array of elements and return an array containing unique elements. If an element is an object or array:

  • when prop is undefined, uses JSON.stringify() when checking the elements
  • when prop is provided, only that property needs to match for the element to be considered a duplicate and thus excluded from the returned array

Returns: array - A new filtered array

| Param | Type | Description | | --- | --- | --- | | arr | array | Array to be filtered by uniqueness of elements (or property of elements) | | [prop] | any | Optional property to be tested if an element in arr is an object or array |

Example

const array1 = [1, 2, 3, 2, 5, 1];
const uniq = unique(array1);
console.log(uniq);
// Logs: [1, 2, 3, 5]

diff(array1, array2, [prop]) ⇒ array

Return a subset of array1, only including elements that are NOT also in array2. The returned array won't include any elements from array2. If an element is an object or array:

  • when prop is undefined, uses JSON.stringify() when performing the comparison on an object or array
  • when prop is provided, only that property needs to match for the item to be excluded fom the returned array

Returns: array - A filtered array

| Param | Type | Description | | --- | --- | --- | | array1 | array | Array for which to return a subset | | array2 | array | Array to use as a comparison | | [prop] | string | Optional property to be tested if an element in array1 is an object or array |

Example

const array1 = [1, 2, 3, 4];
const array2 = [2, 3, 5, 6, -1];
console.log(diff(array1, array2));
// Logs: [1, 4]

chunk(arr, n) ⇒ array

From an array passed into the first argument, create an array of arrays, each one consisting of n items. (The final nested array may have fewer than n items.)

Returns: array - A new, chunked, array

| Param | Type | Description | | --- | --- | --- | | arr | array | Array to be chunked. This array itself will not be modified. | | n | number | Number of elements per chunk |

range(a, [b]) ⇒ array

Create an array of numbers from 0 to a - 1 (if b not provided) or from a to b (if b is provided).

Returns: array - A new array of numbers

| Param | Type | Description | | --- | --- | --- | | a | number | The length of the 0-based array to be returned if b is NOT provided; the first number in the array if b IS provided. | | [b] | number | The (optional) last number of the array. |

pad(arr, size, value) ⇒ array

Pad an array with value until its length equals size

Returns: array - The array passed to arr, padded

| Param | Type | Description | | --- | --- | --- | | arr | array | Array to pad | | size | number | Total length of the array after padding it | | value | any | Value to use for each "padded" element of the array |

sort(arr, [prop], [options]) ⇒ array

Sort an array with sensible defaults: numbers (or numeric strings) before letters and case and diacritics ignored

Returns: array - The sorted array

| Param | Type | Default | Description | | --- | --- | --- | --- | | arr | array | | Array to sort | | [prop] | string | | If dealing with an array of objects, the property by which to sort | | [options] | object | | Object indicating options to override defaults (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator#options) | | [options.sensitivity] | string | "base" | One of 'base', 'accent', 'case', 'variant'. Default is 'base' | | [options.numeric] | boolean | true | Whether to treat numeric strings as numbers. Default is true | | [options[...rest]] | any | | Other options (besides sensitivity:'base' and numeric: true) per the spec for Intl.Collator.prototype.compare |

color

ESM Import Example

import {rgb2Hex} from 'ksjs'

// or:
import {rgb2Hex} from 'ksjs/color.mjs'
// or:
import {rgb2Hex} from 'ksjs/color.js'

CJS Require Example

const {rgb2Hex} = require('ksjs/color.cjs');
// or:
const {rgb2Hex} = require('ksjs/cjs/color.js');

hex2Rgb

Convert a hex value to an rgb or rgba value

| Param | Type | Description | | --- | --- | --- | | hex | string | Hex color code in shorthand format (e.g. #333, #333a) or longhand (e.g. #333333, #333333aa) | | [alpha] | number | Optional number from 0 to 1 to be used with 3- or 6-character hex format |

rgb2Hex(rgb) ⇒ string

Convert an rgb value to a 6-digit hex value. If an rgba value is passed, the opacity is ignored

Returns: string - Hex value (e.g. #ff780a)

| Param | Type | Description | | --- | --- | --- | | rgb | string | array | either an rgb string such as 'rgb(255, 120, 10)' or an rgb array such as [255, 120, 10] |

Example

rgb2Hex('rgb(255, 136, 0)')
// => '#ff8800'

rgb2Hex([255, 136, 0])
// => '#ff8800'

rgb2Hex('rgba(255, 136, 0, .8)')
// => '#ff8800'

rgba2Hex(rgba) ⇒ string

Convert an rgba value to an 8-digit hex value, or an rgb value to a 6-digit hex value

Returns: string - Hex value (e.g. #ff780a80)

| Param | Type | Description | | --- | --- | --- | | rgba | string | array | either an rgba string such as 'rgba(255, 120, 10, .5)' or an rgba array such as [255, 120, 10, .5] |

Example

rgba2Hex('rgba(255, 136, 0, .8)')
// => '#ff8800cc'

rgba2Hex([255, 136, 0, .8])
// => '#ff8800cc'

rgba2Hex('rgb(255, 136, 0)')
// => '#ff8800'

rgb2Luminance(rgb) ⇒ number

Convert an RGB color to a luminance value. You probably don't want to use this on its own

Returns: number - The luminance value

See

| Param | Type | Description | | --- | --- | --- | | rgb | string | array | RGB value represented as a string (e.g. rgb(200, 100, 78)) or an array (e.g. [200, 100, 78]) |

getContrastColor(bgColor, [darkColor], [lightColor]) ⇒ string

Return darkColor if bgColor is light and lightColor if bgColor is dark. "Light" and "dark" are determined by the rgb2Luminance algorithm

Returns: string - Contrasting color

  • Warning: untested

| Param | Type | Default | Description | | --- | --- | --- | --- | | bgColor | string | | hex code (e.g. #daf or #3d31c2) of the color to contrast | | [darkColor] | string | "'#000'" | The dark color to return if bgColor is considered light | | [lightColor] | string | "'#fff'" | The light color to return if bgColor is considered dark |

cookie

ESM Import Example:

import {getCookie} from 'ksjs';

// or:
import {getCookie} from 'ksjs/cookie.mjs';
// or:
import {getCookie} from 'ksjs/cookie.js';

getCookie(name) ⇒ string

Get the value of a cookie

Returns: string - value The value of the cookie

| Param | Type | Description | | --- | --- | --- | | name | string | The name of the cookie whose value you wish to get |

setCookie(name, value, [options]) ⇒ string

Set the value of a cookie. Use either expires or maxAge (or max-age). NOT BOTH.

Returns: string - The new cookie

| Param | Type | Default | Description | | --- | --- | --- | --- | | name | string | | Name of the cookie | | value | string | | Value of the cookie | | [options] | object | | Optional object | | [options.path] | string | "'/'" | Path within which the cookie can be read. Default is '/'. | | [options.domain] | string | | If not specified, browser defaults to host portion of current location. If domain specified, subdomains always included. (Note: don't use leading "."). Default is undefined. | | [options.expires] | number | | Number of days after which the cookie should expire. Default is undefined. | | [options.maxAge] | number | | Number of seconds after which the cookie should expire. Default is undefined. | | [options.samesite] | string | | One of 'strict' or 'lax'. Default is undefined. | | [options.secure] | boolean | | If true, cookie can only be sent over secure protocol (e.g. https). Default is undefined. |

removeCookie(name, [path])

Remove a cookie

| Param | Type | Description | | --- | --- | --- | | name | string | Name of the cookie to remove | | [path] | string | Optional path of the cookie to remove. If not provided, all name cookies in location.pathname or any of its parents will be removed. |

dom

ESM Import Example:

import {addClass} from 'ksjs';

// or:
import {addClass} from 'ksjs/dom.mjs';
// or:
import {addClass} from 'ksjs/dom.js';

toNodes(element(s)) ⇒ array

Converts a selector string, DOM element, or collection of DOM elements into an array of DOM elements

Returns: array - An array of DOM elements

| Param | Type | Description | | --- | --- | --- | | element(s) | Element | NodeList | array | string | The selector string, element, or collection of elements (NodeList, HTMLCollection, Array, etc) |

$(selector, [context]) ⇒ Array

Return an array of DOM Nodes within the document or provided element/nodelist

Returns: Array - Array of DOM nodes matching the selector within the context

| Param | Type | Default | Description | | --- | --- | --- | --- | | selector | string | | The CSS selector of the DOM elements | | [context] | Element | NodeList | array | string | document | The selector string, element, or collection of elements (NodeList, HTMLCollection, Array, etc) representing one or more elements within which to search for selector |

$1(selector, [context]) ⇒ Element

Return the first found DOM Element within the document or provided element/nodelist/HTMLCollection

Returns: Element - First DOM Element matching the selector within the context

| Param | Type | Default | Description | | --- | --- | --- | --- | | selector | string | | Selector string for finding the DOM element | | [context] | Element | NodeList | array | string | document | The selector string, element, or collection of elements (NodeList, HTMLCollection, Array, etc) representing one or more elements within which to search for selector |

addClass(el, className, [...classNameN]) ⇒ string

Add one or more classes to an element

Returns: string - the resulting class after classes have been removed

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element for which to add the class | | className | string | class to add to the DOM element | | [...classNameN] | string | one or more additional className arguments representing classes to add to the element |

removeClass(el, className, [...classNameN]) ⇒ string

Remove one or more classes from an element

Returns: string - the resulting class after classes have been removed

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element from which to remove the class | | className | string | class to remove from the DOM element | | [...classNameN] | string | one or more additional className arguments representing classes to remove from the element |

toggleClass(el, className, [toggle]) ⇒ string

Add a class if it's not present (or if toggle is true); remove the class if it is present (or if toggle is false)

Returns: string - The className property of the element after the class has been toggled

| Param | Type | Description | | --- | --- | --- | | el | Element | Element on which to toggle the class | | className | string | The class name to either add or remove | | [toggle] | boolean | Optional boolean argument to indicate whether className is to be added (true) or removed (false) |

replaceClass(el, oldClass, newClass) ⇒ string

Replace oldClass with newClass

Returns: string - The className property of the element after the class has been replaced

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element for which you want to replace oldClass with newClass | | oldClass | string | The class name you want to get rid of | | newClass | string | The class name you want to add in place of oldClass |

getOffset(el) ⇒ Object

Get the top and left distance to the element (from the top of the document)

Returns: Object - Object with top and left properties representing the top and left offset of the element

  • Warning: untested

| Param | Type | Description | | --- | --- | --- | | el | Element | Element for which to get the offset |

setStyles(el, styles) ⇒ Element

Set one or more styles on an element.

Returns: Element - The original element, with the styles set

| Param | Type | Description | | --- | --- | --- | | el | Element | element on which to add styles | | styles | Object.<string, (string|number)> | object of styles and their values to add to the element |

setAttrs(el, attrs) ⇒ Element

Set one or more attributes on an element. For boolean attributes ('async', 'required', etc.), set the element's property to either true or false

Returns: Element - The original element, with the attributes set

| Param | Type | Description | | --- | --- | --- | | el | Element | element on which to add attributes | | attrs | Object.<string, (string|boolean|number)> | object of attributes and their values to add to the element |

getAttrs(el, attrs) ⇒ Object

Given an array of attribute names, get an object containing attribute names/values for an element

Returns: Object - Object of attribute names along with their values

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM Element. If NodeList is provided, uses the first element in the list | | attrs | Array.<string> | Array of attribute names |

toggleAttr(el, attribute, [toggle]) ⇒ string

Add an attribute to an element if it's not present (or if toggle is true); remove the attribute if it is present (or if toggle is false)

Returns: string - The attribute name if it has been added, undefined if it has been removed

| Param | Type | Description | | --- | --- | --- | | el | Element | Element on which to toggle the attribute | | attribute | string | The attribute to either add or remove | | [toggle] | boolean | Optional boolean argument to indicate whether the attribute is to be added (true) or removed (false) * |

insertHTML(element, position, toInsert)

| Param | Type | Description | | --- | --- | --- | | element | Element | html element | | position | string | position for insertion | | toInsert | string | html string to insert |

prepend(el, toInsert) ⇒ Element

Insert an element as the first child of el

Returns: Element - The inserted element

| Param | Type | Description | | --- | --- | --- | | el | Element | Reference element | | toInsert | Element | string | DOM element or HTML string to insert as the first child of el |

append(el, toInsert) ⇒ Element

Insert an element as the last child of el

Returns: Element - The inserted element

| Param | Type | Description | | --- | --- | --- | | el | Element | Reference element | | toInsert | Element | string | DOM element or HTML string to insert as the last child of el |

before(el, toInsert) ⇒ Element

Insert an element as the previous sibling of el

Returns: Element - The inserted element

| Param | Type | Description | | --- | --- | --- | | el | Element | Reference element | | toInsert | Element | string | DOM element or HTML string to insert as the previous sibling of el |

after(el, toInsert) ⇒ Element

Insert an element as the next sibling of el

Returns: Element - The inserted element

| Param | Type | Description | | --- | --- | --- | | el | Element | Reference element | | toInsert | Element | string | DOM element or HTML string to insert as the next sibling of el |

createTree(options) ⇒ Element(s)

Provide an object, along with possible child objects, to create a node tree ready to be inserted into the DOM.

Returns: Element(s) - The created Element node tree

| Param | Type | Description | | --- | --- | --- | | options | object | | | [options.tag] | string | Optional tag name for the element. If none provided, a document fragment is created instead | | [options.text] | string | Optional inner text of the element. | | [options.children] | Array.<Object> | Optional array of objects, with each object representing a child node | | [...options[attr]] | string | One or more optional attributes to set on the element |

createHTML(options) ⇒ Element(s)

Provide an object, along with possible child objects, to create an HTML string that can be inserted into the DOM.

Returns: Element(s) - The created Element node tree

| Param | Type | Description | | --- | --- | --- | | options | object | | | [options.tag] | string | Optional tag name for the element. If none provided, a document fragment is created instead | | [options.text] | string | Optional inner text of the element. | | [options.children] | Array.<Object> | Optional array of objects, with each object representing a child node | | [...options[attr]] | string | One or more optional attributes to set on the element |

remove(el) ⇒ Element

Remove an element from the DOM

Returns: Element - DOM element removed from the DOM

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element to be removed |

empty(el) ⇒ Element

Empty an element's children from the DOM

Returns: Element - DOM element provided by el argument

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element to clear of all children |

replace(oldEl, replacement)

Replace a DOM element with one or more other elements

| Param | Type | Description | | --- | --- | --- | | oldEl | Element | The element to be replaced | | replacement | Element | Array.<Element> | An element, or an array of elements, to insert in place of oldEl |

loadScript(options) ⇒ Promise

Insert a script into the DOM with reasonable default properties, returning a promise. If options.id is set, will avoid loading script if the id is already in the DOM.

Returns: Promise - Promise that is either resolved or rejected. If options.id is NOT provided or if no element exists with id of options.id, promise is resolved when script is loaded. If options.id IS provided and element with same id exists, promise is resolved or rejected (depending on options.onDuplicateId) with no attempt to load new script.

| Param | Type | Default | Description | | --- | --- | --- | --- | | options | object | | An object of options for loading the script. All except complete and completeDelay will be set as properties on the script element before it is inserted. | | [options.src] | string | | The value of the script's src property. Required if options.textContent not set | | [options.textContent] | string | | The text content of the script. Ignored if options.src set. Required if options.src NOT set. | | [options.async] | boolean | true | The value of the script's async property. Default is true. | | [options.completeDelay] | number | 0 | Number of milliseconds to wait when the script has loaded before resolving the Promise to account for time it might take for the script to be parsed | | [options.id] | string | | String representing a valid identifier to set as the script element's id property. If set, the script will not be loaded if an element with the same id already appears in the DOM | | [options.onDuplicateId] | string | "resolve" | One of 'resolve' or 'reject'. Whether to return a resolved or rejected promise when a script with an id matching the provided options.id is already in the DOM. Either way, the function will not attempt to load the script again and the resolved/rejected promise will be passed an object with {duplicate: true}. | | [...options[scriptProperties]] | boolean | string | | Any other values to be set as properties of the script element |

event

ESM Import Example:

import {addEvent} from 'ksjs';

// or:
import {addEvent} from 'ksjs/event.mjs';
// or:
import {addEvent} from 'ksjs/event.js';

addEvent(el, type, handler(event), [options])

A wrapper around addEventListener that deals with browser inconsistencies (e.g. capture, passive, once props on options param; see param documentation below for details) and handles window load similar to how jQuery handles document ready by triggering handler immediately if called after the event has already fired. For triggering window load, this file MUST be imported before window.load occurs.

| Param | Type | Default | Description | | --- | --- | --- | --- | | el | Window | Element | | DOM element to which to attach the event handler | | type | string | | Event type | | handler(event) | function | | Handler function. Takes event as its argument | | [options] | Object | boolean | false | Optional object or boolean. If boolean, indicates whether the event should be in "capture mode" rather than starting from innermost element and bubbling out. Default is false. If object, and browser does not support object, argument is set to capture property if provided | | [options.capture] | boolean | false | Indicates if the event should be in "capture mode" rather than starting from innermost element and bubbling out. Default is false. | | [options.passive] | boolean | | If true, uses passive mode to reduce jank. This is automatically set to true for supported browsers if not explicitly set to false for the following event types: touchstart, touchmove, wheel, mousewheel. Ignored if not supported. | | [options.once] | boolean | | If true, removes listener after it is triggered once on the element. |

removeEvent(el, type, [handler], [options])

A wrapper around removeEventListener that naïvely deals with oldIE inconsistency.

| Param | Type | Default | Description | | --- | --- | --- | --- | | el | Element | | DOM element to which to attach the event handler | | type | string | | Event type. | | [handler] | function | | Handler function to remove. | | [options] | Object | boolean | false | Optional object or boolean. If boolean, indicates whether event to be removed was added in "capture mode". Important: non-capturing here only removes non-capturing added event and vice-versa. | | [options.capture] | boolean | | Indicates whether event to be removed was added in "capture mode" |

triggerEvent(el, type, detail)

Trigger a custom event on an element for which a listener has been set up

Derived from emitEvent(): (c) 2019 Chris Ferdinandi, MIT License, https://gomakethings.com

| Param | Type | Description | | --- | --- | --- | | el | Element | DOM element on which to trigger the event | | type | string | Name representing the custom event type | | detail | Object | Object to make available as the detail property of the event handler's event argument |

Example

// Using this module's addEvent() function
// Add a custom event handler
addEvent(document.body, 'myCustomEvent', (event) => console.log(event.detail.weather));

// Later…
// Trigger the custom event
triggerEvent(document.body, 'myCustomEvent', {weather: 'sunshine'});
// Logs: 'sunshine'

form

ESM Import Example:

import {getFormData} from 'ksjs';

// or:
import {getFormData} from 'ksjs/form.mjs';
// or:
import {getFormData} from 'ksjs/form.js';

getFormData ⇒ any

Return the set of successful form controls of the provided form element in one of four types: object, string, formData, or array.

Returns: any - The set of successful form controls as the provided type

| Param | Type | Default | Description | | --- | --- | --- | --- | | form | Element | | The form element | | [type] | string | "object" | One of 'object', 'string', 'formData', or 'array' |

Methods

| Name | Type | Description | | --- | --- | --- | | .object(form) | function | Return form data as an object of key/value pairs | | .string(form) | function | Return form data as a query string | | .formData(form) | function | Return a FormData instance | | .array(form) | function | Return form data as an array of objects with name and value properties |

Example

const myform = document.getElementById('myform');

console.log(getFormData.object(myform));
// Logs:
// {
//    email: '[email protected]',
//    gender: 'female',
//    meals: ['breakfast', 'dinner']
// }

Example

const myform = document.getElementById('myform');

console.log(getFormData.string(myform));
// Logs:
// email=name%40example.com&gender=female&meals[]=breakfast&meals[]=dinner

Example

const myform = document.getElementById('myform');

console.log(getFormData.array(myform));
// Logs:
// [
//    {
//      name: 'email',
//      value: '[email protected]'
//    },
//    {
//      name: 'gender',
//      value: 'femail'
//    },
//    {
//      name: 'meals[]',
//      value: 'breakfast'
//    },
//    {
//      name: 'meals[]',
//      value: 'dinner'
//    }
// ]

valuesToFormData(values) ⇒ FormData

Note: if the value of a key is an object with a files property, each file in the files array will be appended to the FormData object.

Returns: FormData - The form data object

| Param | Type | Description | | --- | --- | --- | | values | Object | Array | The object or array of objects to convert |

jsonp

ESM Import Example:

import {getJSONP} from 'ksjs';

// or:
import {getJSONP} from 'ksjs/jsonp.mjs';
// or:
import {getJSONP} from 'ksjs/jsonp.js';

getJSONP(options, callback(json))

Function for those times when you just need to make a "jsonp" request (and you can't set up CORS on the server). In other words, x-site script grabbing.

  • Warning: untested
  • Warning: requires setup on server side
  • Warning: not entirely safe

| Param | Type | Default | Description | | --- | --- | --- | --- | | options | Object | | | | options.url | string | | URL of the jsonp endpoint | | [options.data] | Object | | Optional data to include with the request | | [options.data.callback] | string | "jsonp.[timestamp]" | Optional value of the callback query-string parameter to append to the script's src | | callback(json) | function | | Function to be called when request is complete. A json object is passed to it. |

Example

getJSONP({url: 'https://example.com/api/'})

math

ESM Import Example:

import {median} from 'ksjs';

// or:
import {median} from 'ksjs/math.mjs';
// or:
import {median} from 'ksjs/math.js';

CommonJS Require Example:

const {median} = require('ksjs/math.cjs');
// or:
const {median} = require('ksjs/cjs/math.js');

add(array) ⇒ number

Return the result of adding an array of numbers (sum)

Returns: number - Sum

| Param | Type | Description | | --- | --- | --- | | array | array | Array of numbers |

subtract(array) ⇒ number

Return the result of subtracting an array of numbers (difference)

Returns: number - Difference

| Param | Type | Description | | --- | --- | --- | | array | array | Array of numbers |

multiply(array) ⇒ number

Return the result of multiplying an array of numbers (product)

Returns: number - Product

| Param | Type | Description | | --- | --- | --- | | array | array | Array of numbers |

divide(array) ⇒ number

Return the result of dividing an array of numbers (quotient)

Returns: number - Quotient

| Param | Type | Description | | --- | --- | --- | | array | array | Array of numbers |

mod(dividend, [divisor]) ⇒ number

Return the remainder after dividing two numbers (modulo)

Returns: number - Remainder

| Param | Type | Description | | --- | --- | --- | | dividend | number | array | A number representing the dividend OR an array of [dividend, divisor] | | [divisor] | number | Number representing the divisor if the first argument is a number |

average(nums) ⇒ number

Return the average of an array of numbers

Returns: number - Average

| Param | Type | Description | | --- | --- | --- | | nums | array | Array of numbers |

median(nums) ⇒ number

Return the median of an array of numbers

Returns: number - Median

| Param | Type | Description | | --- | --- | --- | | nums | array | Array of numbers |

min(nums) ⇒ number

Return the number with the lowest value from an array of numbers

Returns: number - Minimum value

| Param | Type | Description | | --- | --- | --- | | nums | array | Array of numbers |

max(nums) ⇒ number

Return the number with the highest value from an array of numbers

Returns: number - Maximum value

| Param | Type | Description | | --- | --- | --- | | nums | array | Array of numbers |

object

ESM Import Example:

import {deepCopy} from 'ksjs';

// or:
import {deepCopy} from 'ksjs/object.mjs';
// or:
import {deepCopy} from 'ksjs/object.js';

CommonJS Require Example:

import {deepCopy} from 'ksjs/object.cjs';
// or:
const {deepCopy} = require('ksjs/cjs/object.js');

isObject(obj)

Indicate if the provided argument is an object/array

| Param | Type | Description | | --- | --- | --- | | obj | Object | The argument that will be checked to see if it is an object |

isPlainObject(obj)

Indicate if the provided argument is a plain object Derived from lodash _.isPlainObject

| Param | Type | Description | | --- | --- | --- | | obj | Object | The argument that will be checked to see if it is a plain object |

clone(obj) ⇒ Object

Deep copy an object (alternative to deepCopy), using graph theory and new Map(). Avoids circular refs and infinite loops.

Returns: Object - A copy of the object

See: Cloning JavaScript objects with Graph Theory

| Param | Type | | --- | --- | | obj | Object |

deepCopy(obj, [forceFallback], [cache]) ⇒ Object

Deep copy an object, avoiding circular references and the infinite loops they might cause.

Returns: Object - A copy of the object

| Param | Type | Description | | --- | --- | --- | | obj | Object | The object to copy | | [forceFallback] | Boolean | If set to true, doesn't try to use native structuredClone function first. | | [cache] | Array.<Object> | Used internally to avoid circular references |

isDeepEqual(objectA, objectB) ⇒ Boolean

Compare two items for equality, recursing through nested objects or arrays

Returns: Boolean - True if the items are deeply equal, false otherwise

| Param | Type | Description | | --- | --- | --- | | objectA | * | The first item to compare | | objectB | * | The second item to compare |

extend(target, ...objects) ⇒ Object

Deep merge two or more objects in turn, with right overriding left

Heavily influenced by/mostly ripped off from jQuery.extend

Returns: Object - The merged object

| Param | Type | Description | | --- | --- | --- | | target | Object | The target object that will be mutated. Use {} to create new object | | ...objects | Object | One or more objects to merge into the first |

Example

const foo = {
  one: 'singular',
  two: 'are better'
};

const bar = {
  one: 'taste',
  choco: 'hershey',
  saloon: 'wild west',
};

const merged = extend(foo, bar);

// merged is now:
// {
//  one: 'taste',
//  two: 'are better',
//  choco: 'hershey',
//  saloon: 'wild west',
// }


// because foo was mutated, it is also:
// {
//  one: 'taste',
//  two: 'are better',
//  choco: 'hershey',
//  saloon: 'wild west',
// }

getProperty(root, properties, fallbackValue) ⇒ *

Get a nested property of an object in a safe way

Returns: * - The value of the nested property, or undefined, or the designated fallback value

| Param | Type | Description | | --- | --- | --- | | root | Object | The root object | | properties | Array.<String> | String | Either an array of properties or a dot-delimited string of properties | | fallbackValue | any | A value to assign if it's otherwise undefined |

Example

const foo = {
  could: {
   keep: {
    going: 'but will stop'
  }
};

console.log(getProperty(foo, 'could.keep.going'))
// Logs: 'but will stop'

console.log(getProperty(foo, ['could', 'keep', 'going']))
// Logs: 'but will stop'

console.log(getProperty(foo, ['broken', 'not', 'happening']))
// Logs: undefined
};

getLastDefined(root, properties) ⇒ *

Get a nested property of an object in a safe way

Returns: * - The value of the last nested property referenced in properties arg that has a defined value

| Param | Type | Description | | --- | --- | --- | | root | Object | The root object | | properties | Array.<String> | String | Either an array of properties or a dot-delimited string of properties |

Example

const foo = {
  could: {
   keep: {
    going: 'but will stop'
  },
  shortStop: 'ride ends here'
};

console.log(getLastDefined(foo, 'could.keep.going'))
// Logs: 'but will stop'

console.log(getLastDefined(foo, ['shortStop', 'stops', 'short']))
// Logs: 'ride ends here'
};

isEmptyObject(obj) ⇒ boolean

Determine whether an object (or array) is "empty"

Returns: boolean - true if object has no keys or array no elements

| Param | Type | Description | | --- | --- | --- | | obj | object | array | The object to test |

setProperty(root, properties, value) ⇒ Object

Set a nested property of an object in a safe way

Returns: Object - The modified root object

| Param | Type | Description | | --- | --- | --- | | root | Object | The root object | | properties | Array.<String> | String | Either an array of properties or a dot-delimited string of properties | | value | any | The value to set for the nested property |

forEachValue(obj, fn) ⇒ void

Loop through an object, calling a function for each element (like forEach, but for an object)

| Param | Type | Description | | --- | --- | --- | | obj | Object | The object to iterate over | | fn | function | A function to be called for each member of the object. The function takes two parameters: the member's value and the member's key, respectively |

getObject(obj, options)

INTERNAL: Return either the same object passed in first parameter or a deep copy of the object, depending on the deep option.

| Param | Type | Description | | --- | --- | --- | | obj | Object | The object to return | | options | Object | Options object | | options.deep | boolean | Whether to deep-clone the object or not before returning it |

pick(obj, props, [options]) ⇒ Object

Return a new object containing only the properties included in the props array.

Returns: Object - A copy of the object, containing only the props properties

| Param | Type | Default | Description | | --- | --- | --- | --- | | obj | Object | | The object from which to get properties | | props | array.<string> | | Properties to get from the object | | [options] | Object | | Options object | | [options.deep] | boolean | true | Whether to deep-clone the object before assigning its properties to the new object |

omit(obj, props, [options]) ⇒ Object

Return a new object, excluding the properties in the props array.

Returns: Object - A modified copy of the object

| Param | Type | Default | Description | | --- | --- | --- | --- | | obj | Object | | The object from which to get properties | | props | array | | Properties to exclude from the object | | [options] | Object | | Options object | | [options.deep] | boolean | true | Whether to deep-clone the object before assigning its properties to the new object |

promise

ESM Import Example:

import {peach} from 'ksjs';

// or:
import {peach} from 'ksjs/promise.mjs';
// or:
import {peach} from 'ksjs/promise.js';

CommonJS Require Example:

import {peach} from 'ksjs/promise.cjs';
// or:
const {peach} = require('ksjs/cjs/promise.js');

peach(arr, fn) ⇒ Array.<Promise>

"Promised each()" for iterating over an array of items, calling a function that returns a promise for each one. So, each one waits for the previous one to resolve before being called

Returns: Array.<Promise> - Array of promises

| Param | Type | Description | | --- | --- | --- | | arr | array | Array to iterate over | | fn | ArrayCallback | Function that is called for each element in the array, each returning a promise |

pmap(arr, fn, [order]) ⇒ Promise

"Promised map()" for iterating over an array of items sequentially (or in parallel), calling a function that returns either the Promise of a modified item or the modified item itself, ultimately returning a single resolved Promise containing the modified array.

Returns: Promise - A resolved Promise, fulfilled with an array containing the mapped items of arr

| Param | Type | Default | Description | | --- | --- | --- | --- | | arr | array | | Array to iterate over | | fn | ArrayCallback | | Function that is called for each element in the array, each returning a modified result | | [order] | string | "sequence" | Whether to call the callback for each item sequentially ('sequence', default) or at the same time ('parallel'). |

Example

import {pmap} from 'ksjs/promise.js';

const fruits = ['apple', 'banana', 'pear'];

const indexedFruits = pmap(fruits, (fruit, i) => {

});

pfilter(arr, fn(item,index,array), [order]) ⇒ Promise

"Promised filter()" to iterate over an array of items sequentially (or in parallel), which acts just like Array.prototype.filter() but allows the callback function to return either a Promise containing a truthy/falsy value or the truthy/falsy value itself. Returns a single resolved Promise containing the filtered array.

Returns: Promise - A resolved Promise, fulfilled with an array containing the mapped items of arr

| Param | Type | Default | Description | | --- | --- | --- | --- | | arr | array | | Array to iterate over | | fn(item,index,array) | ArrayCallback | | Function that is called for each element in the array, each returning a modified result | | [order] | string | "sequence" | Whether to call the callback for each item se