slice-like

Creates an Array from a slice of an Array-like object

Usage no npm install needed!

<script type="module">
  import sliceLike from 'https://cdn.skypack.dev/slice-like';
</script>

README

slice-like

Version License Build Coverage Dependencies

Creates an Array from a slice of an Array-like object.

Install

Install via npm:

npm install --save slice-like

Usage

Convert an Array-like object to an Array

Pass any Array-like object — an object with a 'length' property and numerical indices — in order to convert it to an Array.

const sliceLike = require('slice-like');

var arrayLike = {
  0: 'zero',
  1: 'one',
  length: 2
};

var arr = sliceLike(arrayLike); // => ['zero', 'one'];

An Alternative to Rest Parameters

This module may be used in place of rest parameters in environments where they are unsupported. Pass the arguments object and the index at which the rest parameters start, as follows:

function someFunction(firstParam, secondParam /*, ...restParams */) {
  var restParams = sliceLike(arguments, 2);
  // ...
}

API

sliceLike(arrayLike, [start], [end])

Slices an Array-like object and returns an Array. Slicing behavior is similar to the Array.prototype.slice() method.

Parameters

Param Type Description
arrayLike object An object with a 'length' property and indexed elements, e.g., the arguments object.
[start] number The index at which to start the slice. The resulting Array includes the start index. Defaults to the beginning of `arrayLike`.
[end] number The index at which to end the slice. The resulting Array does not include the end index. Defaults to the end of `arrayLike`.

Returns

Type: Array

The resulting Array, sliced according to the start and/or end arguments if provided.

License

Copyright © 2016 Akim McMath. Licensed under the MIT License.