Skip to content

Commit 1ff0282

Browse files
committed
feat(join): Flatten before joining
1 parent 879c1d1 commit 1ff0282

File tree

4 files changed

+40
-1
lines changed

4 files changed

+40
-1
lines changed

internal/flatten.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
var isArray = Array.isArray
2+
3+
module.exports = function flatten(vals) {
4+
var result = []
5+
var n = vals.length
6+
var i = -1
7+
var val
8+
9+
while (++i < n) {
10+
val = vals[i]
11+
12+
if (isArray(val)) {
13+
result.push.apply(result, flatten(val))
14+
} else {
15+
result.push(val)
16+
}
17+
}
18+
19+
return result
20+
}

join.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
var tuple = require('./tuple')
2+
var flatten = require('./internal/flatten')
23

34
function join(a, b, c) {
45
return b != null && c == null ? joinCurried(a, b) : joinMain(a, b, c)
56
}
67

78
function joinMain(id, joiner, makerFns) {
8-
var result = tuple(id, makerFns)
9+
var result = flatten(tuple(id, makerFns))
910
return typeof joiner === 'function' ? joiner(result) : result.join(joiner)
1011
}
1112

tests/internal/flatten.test.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const tap = require('tap')
2+
const flatten = require('../../internal/flatten')
3+
4+
tap.test('flatten', t => {
5+
t.deepEquals(flatten([[1, [2, [[3], [[[4]]]]]]]), [1, 2, 3, 4])
6+
t.end()
7+
})
8+
9+
tap.test('empty items', t => {
10+
t.deepEquals(flatten([2, [], 3]), [2, 3])
11+
t.end()
12+
})

tests/join.test.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,3 +6,9 @@ tap.test('function as joiner', t => {
66
t.equals(result, 'a b')
77
t.end()
88
})
9+
10+
tap.test('flattening results', t => {
11+
const result = join(23, ' ', [() => 'a', () => ['b', ['c']]])
12+
t.equals(result, 'a b c')
13+
t.end()
14+
})

0 commit comments

Comments
 (0)