Skip to content
This repository was archived by the owner on Feb 20, 2019. It is now read-only.

Commit 1a2be2c

Browse files
syonipKent C. Dodds
authored andcommitted
feat(initArray): init array with length and prefilled value (#82)
Closes (#81)
1 parent f100041 commit 1a2be2c

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11

2+
import initArray from './init-array'
23
import reduce from './reduce-to-tally'
34
import flatten from './flatten'
45
import getQueryStringParam from './get-query-string-param'
@@ -26,6 +27,7 @@ import dec2bin from './dec2bin'
2627
import searchAndReplace from './search-and-replace'
2728

2829
export {
30+
initArray,
2931
reduce,
3032
flatten,
3133
snakeToCamel,

src/init-array.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
export default initArray
2+
3+
/**
4+
* Original Source:
5+
* http://stackoverflow.com/questions/1295584/most-efficient-way-to-create-a-zero-filled-javascript-array
6+
*
7+
* This method will return an array with the given length, prefilled with given value
8+
*
9+
* @param {Number} len - the length of the array
10+
* @param {*} value - The value to prefill
11+
* @return {Array} - The prefilled array
12+
*/
13+
function initArray(len, value) {
14+
return new Array(len).fill(value)
15+
}

test/init-array.test.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import test from 'ava'
2+
import {initArray} from '../src'
3+
4+
test('inits an array with numbers', t => {
5+
const expected = [7, 7, 7, 7]
6+
const actual = initArray(4, 7)
7+
t.deepEqual(actual, expected)
8+
})
9+
10+
test('inits an array with a string', t => {
11+
const expected = ['pepo', 'pepo', 'pepo', 'pepo']
12+
const actual = initArray(4, 'pepo')
13+
t.deepEqual(actual, expected)
14+
})
15+
16+
test('fills an array with a boolean', t => {
17+
const expected = [false, false, false, false]
18+
const actual = initArray(4, false)
19+
t.deepEqual(actual, expected)
20+
})
21+
22+
test.todo('allow for non-primitive values like objects, arrays, and dates')
23+

0 commit comments

Comments
 (0)