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

Commit d09db9d

Browse files
jsnelgroKent C. Dodds
authored andcommitted
feat(removeFalsy): add removeFalsy function and tests (#150)
1 parent 36a309f commit d09db9d

File tree

3 files changed

+65
-0
lines changed

3 files changed

+65
-0
lines changed

src/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import isNullOrWhitespace from './is-null-or-whitespace'
1919
import isToday from './is-today'
2020
import startsWith from './startsWith'
2121
import removeDuplicates from './remove-duplicates'
22+
import removeFalsy from './remove-falsy'
2223
import add from './add'
2324
import subtract from './subtract'
2425
import subtraction from './subtraction'
@@ -77,6 +78,7 @@ export {
7778
isToday,
7879
startsWith,
7980
removeDuplicates,
81+
removeFalsy,
8082
add,
8183
subtract,
8284
divide,

src/remove-falsy.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
export default removeFalsy
2+
3+
/**
4+
* Original source: https://stackoverflow.com/questions/32906887/remove-all-falsy-values-from-an-array
5+
*
6+
* This method removes any falsy values in an array while maintaining the array's order
7+
* @param {Array} arr - the array filter
8+
*/
9+
10+
function removeFalsy(arr) {
11+
return arr.filter(Boolean)
12+
}

test/remove-falsy.test.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
import test from 'ava'
2+
import {removeFalsy} from '../src'
3+
4+
test('removes false from array', t => {
5+
const n = [false]
6+
const expected = []
7+
const actual = removeFalsy(n)
8+
t.deepEqual(actual, expected)
9+
})
10+
11+
test('removes zero from array', t => {
12+
const n = [0]
13+
const expected = []
14+
const actual = removeFalsy(n)
15+
t.deepEqual(actual, expected)
16+
})
17+
18+
test('removes empty string from array', t => {
19+
const n = ['']
20+
const expected = []
21+
const actual = removeFalsy(n)
22+
t.deepEqual(actual, expected)
23+
})
24+
25+
test('removes null from array', t => {
26+
const n = [null]
27+
const expected = []
28+
const actual = removeFalsy(n)
29+
t.deepEqual(actual, expected)
30+
})
31+
32+
test('removes undefined from array', t => {
33+
const n = [undefined]
34+
const expected = []
35+
const actual = removeFalsy(n)
36+
t.deepEqual(actual, expected)
37+
})
38+
39+
test('removes NaN from array', t => {
40+
const n = [NaN]
41+
const expected = []
42+
const actual = removeFalsy(n)
43+
t.deepEqual(actual, expected)
44+
})
45+
46+
test('maintains array order', t => {
47+
const n = [NaN, 1, 2, false, undefined, 3, 0, '', 4, 5, null]
48+
const expected = [1, 2, 3, 4, 5]
49+
const actual = removeFalsy(n)
50+
t.deepEqual(actual, expected)
51+
})

0 commit comments

Comments
 (0)