-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #73 from uncaughtxcptn/feature/eachIndex-method
Feature/.eachIndex() method
- Loading branch information
Showing
3 changed files
with
54 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.'); | ||
}); |