From 02fedc832271709169a0f55b25fd576ae0f4d908 Mon Sep 17 00:00:00 2001 From: Johnny Zabala Date: Fri, 22 Jun 2018 17:58:22 -0400 Subject: [PATCH] feat(tail): add tail function (#177) Add tail function that returns all but the first element of array. * Return [] for null and undefined Closes #176 --- src/index.js | 2 ++ src/tail.js | 13 +++++++++++++ test/tail.test.js | 27 +++++++++++++++++++++++++++ 3 files changed, 42 insertions(+) create mode 100644 src/tail.js create mode 100644 test/tail.test.js diff --git a/src/index.js b/src/index.js index 4be008fb..079e8d3b 100644 --- a/src/index.js +++ b/src/index.js @@ -63,6 +63,7 @@ import getQueryStringValue from './get-query-string-value' import isLeapYear from './leap-year' import removeElementFromArray from './removeElementFromArray' import generatePassword from './generate-password' +import tail from './tail' export { reverseArrayInPlace, @@ -130,4 +131,5 @@ export { isLeapYear, removeElementFromArray, generatePassword, + tail, } diff --git a/src/tail.js b/src/tail.js new file mode 100644 index 00000000..d9778e9a --- /dev/null +++ b/src/tail.js @@ -0,0 +1,13 @@ +export default tail + +/** + * Original Source: https://stackoverflow.com/a/35361274/5801753 + * + * This function gets all but the first element of array + * + * @param {Array} array - The array to get the tail from + * @return {Array} - The array without the first element + */ +function tail(array) { + return Boolean(array) ? array.slice(1) : [] +} diff --git a/test/tail.test.js b/test/tail.test.js new file mode 100644 index 00000000..d9926221 --- /dev/null +++ b/test/tail.test.js @@ -0,0 +1,27 @@ +import test from 'ava' +import {tail} from '../src' + +test('returns empty array for null', t => { + const expected = [] + const actual = tail(null) + t.deepEqual(actual, expected) +}) + +test('returns empty array for undefined', t => { + const expected = [] + const actual = tail(undefined) + t.deepEqual(actual, expected) +}) + +test('returns empty array for empty array', t => { + const expected = [] + const actual = tail([]) + t.deepEqual(actual, expected) +}) + +test('returns the tail of array', t => { + const original = [1, 2, 3, 4, 5] + const expected = [2, 3, 4, 5] + const actual = tail(original) + t.deepEqual(actual, expected) +})