Socket
Socket
Sign inDemoInstall

fmjs

Package Overview
Dependencies
0
Maintainers
1
Versions
103
Alerts
File Explorer

Advanced tools

Install Socket

Detect and block malicious and high-risk dependencies

Install

    fmjs

A bunch of JavaScript functions that we use a lot at Fusionary.


Version published
Weekly downloads
115
increased by88.52%
Maintainers
1
Install size
533 kB
Created
Weekly downloads
 

Readme

Source

Fusionary JavaScript

view on npm

This repo contains a bunch of plain JavaScript functions that we use often at Fusionary. They are mostly provided as ES6 modules, but a subset of them are also offered as CommonJS modules so they can easily be used in a node.js environment.

Install

If you want to install fmjs via npm or yarn, go ahead:

npm install fmjs
yarn add fmjs

ES6 Modules

If your bundler supports ES6 module tree shaking, you can do import any function like this:

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

(Note: For Webpack, you might need to configure it to treat fmjs as ES6)

Otherwise, for any of the modules, you can do this:

import {example1, example2} from 'fmjs/example'

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

or this (not recommended):

import * as examples from 'fmjs/example'

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

CommonJS Modules

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

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

You can require them from their respective files in the cjs directory, like so:

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

example1('foo');

or like so:

const examples = require('fmjs/cjs/example');

examples.example1('foo');

Modules

ajax

ES6 Import Example:

import {getJSON} from 'fmjs';

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

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

Low-level ajax request

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

ParamTypeDefaultDescription
[url]stringlocation.hrefThe URL of the resource
[options]Object
[options.dataType]stringOne 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]Object | stringData to send along with the request. If it's a GET request and options.data is an object, the object is converted to a query string and appended to the URL.
[options.method]string"GET"One of 'GET', 'POST', etc.
[options.cache]booleantrueIf set to false, will not let server use cached response
[options.memcache]booleanfalseIf set to true, and a previous request sent to the same url was successful, will circumvent request and use the previous response
[options.headers]Object{}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.dataType and options.cache.

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

ParamTypeDefaultDescription
[url]stringlocation.hrefThe 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

ParamTypeDefaultDescription
[url]stringlocation.hrefThe 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

ParamTypeDefaultDescription
[url]stringlocation.hrefThe URL of the resource
[options]Object{}See ajax for details

analytics

ES6 Import Example:

import {analytics} from 'fmjs';

// or:
import {analytics} from 'fmjs/analytics.js';

analytics

Load the google analytics script and set it up to track page views. If the document title has "page not found" in it (case insensitive). It'll prepend /404/ to the url for the page-view tracking.

  • Warning: untested
ParamTypeDescription
idstringThe google analytics ID
[type]stringThe only possible value for the type argument is 'legacy'.

array

ES6 Import Example:

import {isArray} from 'fmjs';

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

CommonJS Require Example:

const {isArray} = require('fmjs/cjs/array.js');

isArray(arr) ⇒ boolean

Determine whether "arr" is a true array

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

ParamTypeDescription
arrarrayitem to determine whether it's an array

Example

import {isArray} from 'fmjs/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)

ParamTypeDescription
elAnyAn item to test against the array
arrarrayThe array to test against

randomItem(arr) ⇒ Any

Return a random item from the provided array

Returns: Any - A random element from the provided array

ParamTypeDescription
arrarrayAn 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)

ParamTypeDescription
arrarrayArray from which to pluck
propstringProperty to pluck

Example

import {pluck} from 'fmjs/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(arr) ⇒ 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

ParamTypeDescription
arrarrayArray to be shuffled

collapse(array1, array2, ...arrays) ⇒ array

Collapse two or more arrays into a single, new array. Same as merge(), but not limited to two arrays.

Returns: array - A new collapsed array

  • Warning: untested

See: merge

ParamTypeDescription
array1arrayFirst array
array2arraySecond array
...arraysarrayAdditional arrays to collapse

merge(array1, array2) ⇒ array

Merge two arrays into a single, new array. Same as collapse() but only works with two array arguments.

Returns: array - A new merged array

  • Warning: untested

See: collapse

ParamTypeDescription
array1arrayFirst array
array2arraySecond array

intersect(arr1, arr2, [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

ParamTypeDescription
arr1arrayFirst array
arr2arraySecond array
[prop]anyOptional 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

ParamTypeDescription
arrarrayArray to be filtered by uniqueness of elements (or property of elements)
[prop]AnyOptional 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(arr1, arr2, [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

ParamTypeDescription
arr1arrayArray for which to return a subset
arr2arrayArray to use as a comparison
[prop]stringOptional property to be tested if an element in arr1 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, num) ⇒ array

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

Returns: array - A new, chunked, array

ParamTypeDescription
arrarrayArray to be chunked. This array itself will not be modified.
numnumberNumber of elements per chunk

pad(arr, size, value) ⇒ array

Pad an array with value until its length equals size

Returns: array - The array passed to arr, padded

ParamTypeDescription
arrarrayArray to pad
sizenumberTotal length of the array after padding it
valueanyValue to use for each "padded" element of the array

color

ES6 Import Example

import {rgb2Hex} from 'fmjs'

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

CJS Require Example

const {rgb2Hex} = require('fmjs/cjs/color.js');

hex2Rgb

Convert a hex value to an rgb or rgba value

ParamTypeDescription
hexstringHex color code in shorthand format (e.g. #333, #333a) or longhand (e.g. #333333, #333333aa)
[alpha]numberOptional 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)

ParamTypeDescription
rgbstring | arrayeither 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)

ParamTypeDescription
rgbastring | arrayeither 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

ParamTypeDescription
rgbstring | arrayRGB 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
ParamTypeDefaultDescription
bgColorstringhex 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

ES6 Import Example:

import {getCookie} from 'fmjs';

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

getCookie(name) ⇒ string

Get the value of a cookie

Returns: string - value The value of the cookie

ParamTypeDescription
namestringThe 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

ParamTypeDefaultDescription
namestringName of the cookie
valuestringValue of the cookie
[options]ObjectOptional object
[options.path]string"/"Path within which the cookie can be read. Default is '/'
[options.domain]stringIf 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]numberNumber of days after which the cookie should expire. Default is undefined.
[options.maxAge]numberNumber of seconds after which the cookie should expire. Default is undefined.
[options.samesite]stringOne of 'strict' or 'lax'. Default is undefined.
[options.secure]booleanIf true, cookie can only be sent over secure protocol (e.g. https). Default is undefined.

removeCookie(name, [path])

Remove a cookie

ParamTypeDescription
namestringName of the cookie to remove
[path]stringOptional path of the cookie to remove. If not provided, all name cookies in location.pathname or any of its parents will be removed.

dom

ES6 Import Example:

import {addClass} from 'fmjs';

// or:
import {addClass} from 'fmjs/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

ParamTypeDescription
element(s)Element | NodeList | array | stringThe 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

ParamTypeDefaultDescription
selectorstringThe CSS selector of the DOM elements
[context]Element | NodeList | array | stringdocumentThe 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

ParamTypeDefaultDescription
selectorstringSelector string for finding the DOM element
[context]Element | NodeList | array | stringdocumentThe 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

ParamTypeDescription
elElementDOM element for which to add the class
classNamestringclass to add to the DOM element
[...classNameN]stringone 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

ParamTypeDescription
elElementDOM element from which to remove the class
classNamestringclass to remove from the DOM element
[...classNameN]stringone 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

ParamTypeDescription
elElementElement on which to toggle the class
classNamestringThe class name to either add or remove
[toggle]booleanOptional 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

ParamTypeDescription
elElementDOM element for which you want to replace oldClass with newClass
oldClassstringThe class name you want to get rid of
newClassstringThe 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
ParamTypeDescription
elElementElement 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

ParamTypeDescription
elElementelement on which to add styles
stylesObject.<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

ParamTypeDescription
elElementelement on which to add attributes
attrsObject.<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

ParamTypeDescription
elElementDOM Element. If NodeList is provided, uses the first element in the list
attrsarray.<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

ParamTypeDescription
elElementElement on which to toggle the attribute
attributestringThe attribute to either add or remove
[toggle]booleanOptional boolean argument to indicate whether the attribute is to be added (true) or removed (false) *

prepend(el, toInsert) ⇒ Element

Insert an element as the first child of el

Returns: Element - The inserted element

ParamTypeDescription
elElementReference element
toInsertElement | stringDOM 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

ParamTypeDescription
elElementReference element
toInsertElement | stringDOM 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

ParamTypeDescription
elElementReference element
toInsertElement | stringDOM 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

ParamTypeDescription
elElementReference element
toInsertElement | stringDOM 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

ParamTypeDescription
optionsObject
[options.tag]stringOptional tag name for the element. If none provided, a document fragment is created instead
[options.text]stringOptional inner text of the element.
[options.children]Array.<Object>Optional array of objects, with each object representing a child node
[...options[attr]]stringOne 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

ParamTypeDescription
elElementDOM element to be removed

empty(el) ⇒ Element

Empty an element's children from the DOM

Returns: Element - DOM element provided by el argument

ParamTypeDescription
elElementDOM element to clear of all children

replace(oldEl, replacement)

Replace a DOM element with one or more other elements

ParamTypeDescription
oldElElementThe element to be replaced
replacementElement | 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.

ParamTypeDefaultDescription
optionsObjectAn 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]stringThe value of the script's src property. Required if options.textContent not set
[options.textContent]stringThe text content of the script. Ignored if options.src set. Required if options.src NOT set.
[options.async]booleantrueThe value of the script's async property. Default is true.
[options.completeDelay]number0Number 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]stringString 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 | stringAny other values to be set as properties of the script element

event

ES6 Import Example:

import {addEvent} from 'fmjs';

// or:
import {addEvent} from 'fmjs/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.

ParamTypeDefaultDescription
elElementDOM element to which to attach the event handler
typestringEvent type
handler(event)functionHandler function. Takes event as its argument
[options]Object | booleanfalseOptional 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]booleanfalseIndicates if the event should be in "capture mode" rather than starting from innermost element and bubbling out. Default is false.
[options.passive]booleanIf 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]booleanIf 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.

ParamTypeDefaultDescription
elElementDOM element to which to attach the event handler
typestringEvent type.
[handler]functionHandler function to remove.
[options]Object | booleanfalseOptional 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]booleanIndicates 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

ParamTypeDescription
elElementDOM element on which to trigger the event
typestringName representing the custom event type
detailObjectObject 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

ES6 Import Example:

import {getFormData} from 'fmjs';

// or:
import {getFormData} from 'fmjs/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

ParamTypeDefaultDescription
formElementThe form element
[type]string"object"One of 'object', 'string', 'formData', or 'array'

Methods

NameTypeDescription
.object(form)functionReturn form data as an object of key/value pairs
.string(form)functionReturn form data as a query string
.formData(form)functionReturn a FormData instance
.array(form)functionReturn 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: 'name@example.com',
//    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: 'name@example.com'
//    },
//    {
//      name: 'gender',
//      value: 'femail'
//    },
//    {
//      name: 'meals[]',
//      value: 'breakfast'
//    },
//    {
//      name: 'meals[]',
//      value: 'dinner'
//    }
// ]

jsonp

ES6 Import Example:

import {getJSONP} from 'fmjs';

// or:
import {getJSONP} from 'fmjs/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
ParamTypeDefaultDescription
optionsObject
options.urlstringURL of the jsonp endpoint
[options.data]ObjectOptional 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)functionFunction to be called when request is complete. A json object is passed to it.

Example

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

math

ES6 Import Example:

import {median} from 'fmjs';

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

CommonJS Require Example:

const {median} = require('fmjs/cjs/math.js');

add(array) ⇒ number

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

Returns: number - Sum

ParamTypeDescription
arrayarrayArray of numbers

subtract(array) ⇒ number

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

Returns: number - Difference

ParamTypeDescription
arrayarrayArray of numbers

multiply(array) ⇒ number

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

Returns: number - Product

ParamTypeDescription
arrayarrayArray of numbers

divide(array) ⇒ number

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

Returns: number - Quotient

ParamTypeDescription
arrayarrayArray of numbers

mod(dividend, [divisor]) ⇒ number

Return the remainder after dividing two numbers (modulo)

Returns: number - Remainder

ParamTypeDescription
dividendnumber | arrayA number representing the dividend OR an array of [dividend, divisor]
[divisor]numberNumber representing the divisor if the first argument is a number

average(nums) ⇒ number

Return the average of an array of numbers

Returns: number - Average

ParamTypeDescription
numsarrayArray of numbers

median(nums) ⇒ number

Return the median of an array of numbers

Returns: number - Median

ParamTypeDescription
numsarrayArray of numbers

min(nums) ⇒ number

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

Returns: number - Minimum value

ParamTypeDescription
numsarrayArray of numbers

max(nums) ⇒ number

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

Returns: number - Maximum value

ParamTypeDescription
numsarrayArray of numbers

object

ES6 Import Example:

import {deepCopy} from 'fmjs';

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

CommonJS Require Example:

const {deepCopy} = require('fmjs/cjs/object.js');

isObject(obj)

Indicate if the provided argument is an object/array

ParamTypeDescription
objObjectThe 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

ParamTypeDescription
objObjectThe argument that will be checked to see if it is a plain object

deepCopy(obj, [cache]) ⇒ Object

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

Returns: Object - A copy of the object

ParamTypeDescription
objObjectThe object to copy
[cache]Array.<Object>Used internally to avoid circular references

extend(target, ...object) ⇒ 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

ParamTypeDescription
targetObjectThe target object that will be mutated. Use {} to create new object
...objectObjectOne 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, fallbackVaue) ⇒ *

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

ParamTypeDescription
rootObjectThe root object
propertiesArray.<String> | StringEither an array of properties or a dot-delimited string of properties
fallbackVaueAnyA 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
};

isEmptyObject(object) ⇒ boolean

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

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

ParamTypeDescription
objectObject | arrayThe object to test

setProperty(root, properties) ⇒ Object

Set a nested property of an object in a safe way

Returns: Object - The modified root object

ParamTypeDescription
rootObjectThe root object
propertiesarray.<String> | StringEither an array of properties or a dot-delimited string of properties

forEachValue(obj, fn) ⇒ undefined

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

ParamTypeDescription
objObjectThe object to iterate over
fnfunctionA 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

pick(obj, props) ⇒ 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

ParamTypeDescription
objObjectThe object from which to get properties
propsarrayPropertes to get from the object

omit(obj, props) ⇒ Object

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

Returns: Object - A modified copy of the object

ParamTypeDescription
objObjectThe object from which to get properties
propsarrayPropertes to exclude from the object

promise

ES6 Import Example:

import {peach} from 'fmjs';

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

CommonJS Require Example:

const {peach} = require('fmjs/cjs/promise.js');

peach(arr, callback(item,i)) ⇒ 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

ParamTypeDescription
arrarrayArray to iterate over
callback(item,i)callbackFunction that is called for each element in the array, each returning a promise

selection

ES6 Import Example:

import {getSelection} from 'fmjs';

// or:
import {getSelection} from 'fmjs/selection.js';

replaceSelection ⇒ Object

Replace the selected text in a given element with the provided text

Returns: Object - Selection object containing the following properties: {start, end, length, text}

ParamTypeDescription
elemElementElement containing the selected text
replaceStringstringString to replace the selected text

setSelection(elem, [startPos], [endPos])

Set the selection of an element's contents. NOTE: If startPos and/or endPos are used on a non-input element, only the first text node within the element will be used for selection

ParamTypeDefaultDescription
elemElementThe element for which to set the selection
[startPos]number0The start position of the selection. Default is 0.
[endPos]numberThe end position of the selection. Default is the last index of the element's contents.

setSelectionAll(el)

Sets the selection of all of the element's contents (including all of its children)

  • Warning: untested
ParamTypeDescription
elElementThe element for which to select all content

getSelection(el)

Return an object with the following properties related to the selected text within the element:

  • start: 0-based index of the start of the selection
  • end: 0-based index of the end of the selection
  • length: the length of the selection
  • text: the selected text within the element
ParamTypeDescription
elElementAn element with selected text

storage

ES6 Import Example:

import {Storage} from 'fmjs';

// or:
import {Storage} from 'fmjs/storage.js';

getLength() ⇒ number

Get the number of items in the storage

Returns: number - The number of items

get(key) ⇒ Any

Get and JSON.parse the value of the storage item identified by key

Returns: Any - The JSON.parsed value of the storage item

ParamTypeDescription
keystringThe key of the storage item

set(key, value) ⇒ string

Set the JSON.stringified value of the storage item identified by key

Returns: string - The stringified value that is set

ParamTypeDescription
keystringThe key of the storage item
valueAnyThe value to be set for key

remove(key)

Remove the storage item identified by key

ParamTypeDescription
keystringThe key of the storage item to remove

clear()

Remove all storage items

getAll() ⇒ Object

Get an object of key/value pairs of all storage items

Returns: Object - All storage items

keys() ⇒ array

Loop through all storage items and return an array of their keys

Returns: array - Array of the keys of all storage items

Storage

Storage([type], [namespace])

Constructor for storage functions.

ParamTypeDefaultDescription
[type]string"local"Type of storage: either 'local' or 'session'
[namespace]string"fm"Namespace for keys to prevent potenial collisions with storage items used by libraries, etc.

string

ES6 Import Example:

import {slugify} from 'fmjs';

// or:
import {slugify} from 'fmjs/string.js';

CommonJS Require Example:

const {slugify} = require('fmjs/cjs/string.js');

stringTo(value, [type], [options]) ⇒ Boolean | Number | Array

Casts a value to the specified type or to best guess at a type if none given

ParamTypeDescription
valuestringValue to cast
[type]function(Boolean
[options]object

pluralize(str, num, [ending]) ⇒ string

Converts a singular word to a plural

Returns: string - Pluralized string

ParamTypeDefaultDescription
strstringWord to pluralize
numnumberNumber of items
[ending]string"s"Optional ending of the pluralized word

changeCase(str, type) ⇒ string

Changes the case of the provided words according to the type.

Returns: string - Converted string

ParamTypeDescription
strstringString that will be cased as determined by type
typestringOne of 'title

Example

const oldMan = 'the old man and the sea';

console.log(changeCase(oldMan, 'title'));
// Logs: 'The Old Man and the Sea'

console.log(changeCase(oldMan, 'sentence'));
// Logs: 'The old man and the sea'

console.log(changeCase(oldMan, 'camel'));
// Logs: 'theOldManAndTheSea'

slugify(str) ⇒ string

Slugify a string by lowercasing it and replacing white spaces and non-alphanumerics with dashes.

Returns: string - "Slugified" string

ParamTypeDescription
strstringString to be converted to a slug

Example

console.log(slugify('Hello there, how are you?'));
// Logs: 'hello-there-how-are-you'

console.log(slugify('  You? & Me<3* '));
// Logs: 'you-me-3'

commafy(val, [separator]) ⇒ string

Add commas (or provided separator) to a number, or a string representing a number, of 1000 or greater.

Returns: string - number formatted as string

ParamTypeDefaultDescription
valstring | numberNumber to be formatted as a string
[separator]string","punctuation to be used for thousands, millions, etc

rot13(string) ⇒ string

ROT13 encode/decode a string

Returns: string - The encoded (or decoded) string

ParamTypeDescription
stringstringString to be converted to or from ROT13

hashCode(str, [prefix]) ⇒ number | string

Convert a string to Java-like numeric hash code

Returns: number | string - The converted hash code as numeral (or string, if prefix is provided)

See: http://werxltd.com/wp/2010/05/13/javascript-implementation-of-javas-string-hashcode-method/

ParamTypeDescription
strstringString to be converted
[prefix]stringOptional prefix to the hash

base64Encode(str) ⇒ string

Return a base64-encoded string based on the provided string. If the browser does not support this type of encoding, returns the string unchanged.

Returns: string - base64-encoded string

ParamTypeDescription
strstringString to be base4 encoded

base64Decode(str) ⇒ string

Return a decoded string based on the provided base64-encoded string. If the browser does not support this type of encoding, returns the string unchanged.

Returns: string - decoded string

ParamTypeDescription
strstringbase4-encoded string

timer

ES6 Import Example:

import {debounce} from 'fmjs';

// or:
import {debounce} from 'fmjs/timer.js';

CommonJS Require Example:

const {debounce} = require('fmjs/cjs/timer.js');

HOUR : number

Constant representing the number of milliseconds in an hour

DAY : number

Constant representing the number of milliseconds in a day

YEAR : number

Constant representing the number of milliseconds in a year

debounce(fn, [timerDelay], [ctx])

Set up a function to be called once at the end of repeated potential calls within a given delay

ParamTypeDefaultDescription
fnfunctionThe function to trigger once at the end of a series of potential calls within delay
[timerDelay]number200Number of milliseconds to delay before firing once at the end
[ctx]ElementthisThe context in which to call fn

Example

const scrollLog = function(event) {
console.log('Started resizing the window!');
};

window.addEventListener('resize', debounce(scrollLog));

unbounce(fn, [timerDelay], [ctx])

Set up a function to be called once at the end of repeated potential calls within a given delay

ParamTypeDefaultDescription
fnfunctionThe function to trigger once at the beginning of a series of potential calls within delay
[timerDelay]number200Number of milliseconds within which to avoid calling the same function
[ctx]ElementthisThe context in which to call fn

Example

const scrollLog = function(event) {
console.log('Started resizing the window!');
};

window.addEventListener('resize', debounce(scrollLog));

throttle(fn, [timerDelay], [context])

Set up a function to be called no more than once every timerDelay milliseconds

ParamTypeDefaultDescription
fnfunctionThe function to throttle
[timerDelay]number200Number of milliseconds to throttle the function calls
[context]ElementthisThe context in which to call fn

raf(fn, [context])

Set up a function to be called immediately before the next repaint using requestAnimationFrame()

ParamTypeDefaultDescription
fnfunctionThe function to call
[context]ElementthisThe context in which to call fn

url

ES6 Import Example:

import {serialize} from 'fmjs';

// or:
import {serialize} from 'fmjs/url.js';

CommonJS Require Example:

const {serialize} = require('fmjs/cjs/url.js');

pathname([obj]) ⇒ string

Return a normalized pathname (old IE doesn't include initial "/" for this.pathname) of a passed object if it has an href property, or return the derived path name from string representing a URL

Returns: string - pathname

ParamTypeDefaultDescription
[obj]Object | stringwindow.locationAn object with a pathname propety or a string representing a URL

basename([obj], [ext]) ⇒ string

Return the basename of an object with pathname property or a string. Similar to node.js path.basename()

Returns: string - basename

ParamTypeDefaultDescription
[obj]Object | stringwindow.locationAn object with a pathname property, or a string representing a URL
[ext]stringExtension (e.g. '.html') to remove from the end of the basename)

segments([obj]) ⇒ array

Return an array consisting of each segment of a URL path

Returns: array - Array of segments

ParamTypeDefaultDescription
[obj]Object | stringwindow.locationAn object with a pathname property, or a string representing a URL

segment(index, [obj]) ⇒ array

Return the indexth segment of a URL path

Returns: array - A segment of the path derived from obj at index

ParamTypeDefaultDescription
indexnumberIndex of the segment to return. If < 0, works like [].slice(-n)
[obj]Object | stringwindow.locationAn object with a pathname property, or a string representing a URL

serialize(data, [options]) ⇒ string

Convert an object to a serialized string

Returns: string - A query string

ParamTypeDescription
dataObjectPlain object to be serialized
[options]ObjectOptional settings
[options.raw]booleanIf true, property values are NOT url-decoded
[options.prefix]stringIf set, and data is an array, sets as if prefix were the name of the array
[options.arrayToString]indexedIf true, calls .toString() on arrays. So {foo: ['won', 'too']} becomes foo=won%2Ctoo. Used in conjunction with {raw: true}, the same object becomes foo=won,too
[options.indexed]indexedIf true (and options.arrayToString is NOT true), arrays take the form of foo[0]=won&foo[1]=too; otherwise, foo[]=won&foo[]=too

Example

console.log(serialize({foo: 'yes', bar: 'again}));
// Logs: 'foo=yes&bar=again'

Example

console.log(serialize({foo: ['yes', 'again']}, {arrayToString: true}));
// Logs: 'foo=yes,again'
console.log(serialize({foo: ['yes', 'again']}));
// Logs: 'foo[]=yes&foo[]=again'

console.log(serialize({foo: ['yes', 'again']}, {indexed: true}));
// Logs: 'foo[0]=yes&foo[1]=again'

console.log(serialize(['yes', 'again'], {prefix: 'foo'}));
// Logs: 'foo[0]=yes&foo[1]=again'

console.log(serialize(['yes', 'again'], {prefix: 'foo', indexed: false}));
// Logs: 'foo[]=yes&foo[]=again'

unserialize([string], [options]) ⇒ Object

Convert a serialized string to an object

Returns: Object - An object of key/value pairs representing the query string parameters

ParamTypeDefaultDescription
[string]string"location.search"Query string
[options]ObjectOptional options
[options.raw]booleanfalseIf true, param values will NOT be url-decoded
[options.empty]AnytrueThe returned value of a param with no value (e.g. ?foo&bar&baz). Typically, this would be either true or ''
[options.splitValues]Boolean | RegExp | StringfalseIf NOT false, splits converts to an array all values with one or more matches of the splitValues option. If true, splits on commas (/,/). So, ?foo=bar,baz becomes {foo: ['bar', 'baz']}
[options.shallow]booleanfalseIf true, does NOT attempt to build nested object

FAQs

Last updated on 05 Jun 2020

Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc