Skip to content

Commit

Permalink
feat(join): Flatten before joining
Browse files Browse the repository at this point in the history
  • Loading branch information
justinvdm committed May 1, 2020
1 parent 879c1d1 commit 1ff0282
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
20 changes: 20 additions & 0 deletions internal/flatten.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
var isArray = Array.isArray

module.exports = function flatten(vals) {
var result = []
var n = vals.length
var i = -1
var val

while (++i < n) {
val = vals[i]

if (isArray(val)) {
result.push.apply(result, flatten(val))
} else {
result.push(val)
}
}

return result
}
3 changes: 2 additions & 1 deletion join.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
var tuple = require('./tuple')
var flatten = require('./internal/flatten')

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

function joinMain(id, joiner, makerFns) {
var result = tuple(id, makerFns)
var result = flatten(tuple(id, makerFns))
return typeof joiner === 'function' ? joiner(result) : result.join(joiner)
}

Expand Down
12 changes: 12 additions & 0 deletions tests/internal/flatten.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const tap = require('tap')
const flatten = require('../../internal/flatten')

tap.test('flatten', t => {
t.deepEquals(flatten([[1, [2, [[3], [[[4]]]]]]]), [1, 2, 3, 4])
t.end()
})

tap.test('empty items', t => {
t.deepEquals(flatten([2, [], 3]), [2, 3])
t.end()
})
6 changes: 6 additions & 0 deletions tests/join.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,9 @@ tap.test('function as joiner', t => {
t.equals(result, 'a b')
t.end()
})

tap.test('flattening results', t => {
const result = join(23, ' ', [() => 'a', () => ['b', ['c']]])
t.equals(result, 'a b c')
t.end()
})

0 comments on commit 1ff0282

Please sign in to comment.