Skip to content

Commit

Permalink
Merge pull request #73 from uncaughtxcptn/feature/eachIndex-method
Browse files Browse the repository at this point in the history
Feature/.eachIndex() method
  • Loading branch information
arnellebalane authored Jun 2, 2019
2 parents 4f598d2 + 1a65a31 commit 7c9719d
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
4 changes: 3 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import dig from './methods/dig';
import drop from './methods/drop';
import dropWhile from './methods/dropWhile';
import each from './methods/each';
import eachIndex from './methods/eachIndex';

const handlers = {
all,
Expand All @@ -41,7 +42,8 @@ const handlers = {
dig,
drop,
dropWhile,
each
each,
eachIndex
};

export default function rbjs(toProxy) {
Expand Down
24 changes: 24 additions & 0 deletions methods/eachIndex/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* Iterates the items of the array and passes their index to the callback.
*
* @param {Array} array
* @param {Function} callback - The function that will be passed the indeces
* of each array item.
*
* @return {Array} The original given array.
*
* @example
* eachIndex(['a', 'b', 'c'], i => console.log(i)); // prints: 0 1 2
*
* @example
* rbjs(['a', 'b', 'c']).eachIndex(i => console.log(i)); // prints: 0 1 2
*/
export default function eachIndex(array, callback) {
if (typeof callback !== 'function') {
throw new TypeError('Parameter "callback" must be a function.');
}

array.forEach((item, i) => callback(i));

return array;
}
27 changes: 27 additions & 0 deletions methods/eachIndex/tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import test from 'ava';
import eachIndex from '.';

test('passes the index of each item to the callback', t => {
const results = [];
const callback = x => results.push(x);

eachIndex([1, 2, 3, 4, 5], callback);

t.deepEqual(results, [0, 1, 2, 3, 4]);
});

test('returns the given array', t => {
const results = [];
const callback = x => results.push(x);

const array = [1, 2, 3, 4, 5];

t.is(array, eachIndex(array, callback));
});

test('throws TypeError if callback is not provided', t => {
const error = t.throws(() => {
eachIndex([1, 2, 3, 4, 5]);
}, TypeError);
t.is(error.message, 'Parameter "callback" must be a function.');
});

0 comments on commit 7c9719d

Please sign in to comment.