@bemoje/arr-sorted-add

1.0.4 • Public • Published

@bemoje/arr-sorted-add

For a sorted array, add an element. Whichever comparator function was used to sort the array, can be passed. Also supports comparator-builder options. For reference, see: https://github.com/bemoje/bemoje-arr-sort-comparator

Version

NPM version

Travis CI

dependencies

Dependencies

dependencies

Stats

NPM downloads Forks

Donate

Buy Me A Beer donate button PayPal donate button

Installation

npm install @bemoje/arr-sorted-add
npm install --save @bemoje/arr-sorted-add
npm install --save-dev @bemoje/arr-sorted-add

Usage

import arrSortedAdd from '@bemoje/arr-sorted-add'

/**
 * ADD ELEMENT TO SORTED ARRAY
 * Defaults to alphabetically
 */

const alpha = ['a', 'c', 'd']

arrSortedAdd(alpha, 'b')
//=> ['a', 'b', 'c', 'd']

arrSortedAdd(alpha, 'a')
//=> ['a', 'a', 'b', 'c', 'd']

arrSortedAdd(alpha, 'e')
//=> ['a', 'a', 'b', 'c', 'd', 'e']

arrSortedAdd(alpha, '_')
//=> ['_', 'a', 'a', 'b', 'c', 'd', 'e']

/**
 * ADD NUMERICAL VALUES
 */

const numeric = [0, 4, 6]

arrSortedAdd(numeric, 1, {
  numeric: true,
})
//=> [0, 1, 4, 6]

arrSortedAdd(numeric, 5, {
  numeric: true,
})
//=> [0, 1, 4, 5, 6]

arrSortedAdd(numeric, 7, {
  numeric: true,
})
//=> [0, 1, 4, 5, 6, 7]

arrSortedAdd(numeric, 3, {
  numeric: true,
})
//=> [0, 1, 3, 4, 5, 6, 7]

/**
 * To see more examples of using the comparator builder, visit:
 *  https://github.com/bemoje/bemoje-arr-sort-comparator
 */

Tests

Uses Jest to test module functionality. Run tests to get coverage details.

npm run test

API

Table of Contents

arrSortedAdd

For a sorted array, add an element. Whichever comparator function was used to sort the array, can be passed. Also supports comparator-builder options. For reference, see: https://github.com/bemoje/bemoje-arr-sort-comparator

Parameters
  • arr Array The array

  • element any The element for which to find its insertion index

  • compare (function | object)?

    • compare.numeric boolean Sort numerically. Defaults to lexicographic/alphabetic sort. (optional, default false)

    • compare.descending boolean Sort in descending order. Defaults to ascending order. (optional, default false)

    • compare.array boolean Sort arrays. Nested arrays are also compared recursively. (optional, default false)

    • compare.by (number | string | getter) Sort by either array index, a callback(element): any - or by object keys with dot-notation support. (optional, default undefined)

  • duplicates boolean Whether to add the element if a duplicate element exists. (optional, default true)

Returns Array The sorted array

getter

Callback type definition.

Type: Function

Parameters
  • a any The value

Returns any The value to be compared

Package Sidebar

Install

npm i @bemoje/arr-sorted-add

Weekly Downloads

2

Version

1.0.4

License

MIT

Unpacked Size

16.1 kB

Total Files

5

Last publish

Collaborators

  • bemoje