Skip to content

Commit 8d28f73

Browse files
committed
feat: Add intersperse()
1 parent e4d5010 commit 8d28f73

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

src/sequence.js

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1439,6 +1439,29 @@ const zipLongest = curry('zipLongest', (seqs, fallback) => pipe(
14391439
*/
14401440
const zipLongest2 = curry('zipLongest2', (a, b, fallback) => zipLongest([a, b], fallback));
14411441

1442+
/**
1443+
* Inserts an element between every two elements of the given sequence.
1444+
*
1445+
* ```
1446+
* const { intersperse } = require('ferrum');
1447+
* assertSequenceEquals(
1448+
* intersperse('ABC', '|'),
1449+
* ['A', '|', 'B', '|', 'C']);
1450+
* ```
1451+
*
1452+
* @function
1453+
* @param {Any} what – The element to intersperse
1454+
* @param {Sequence} a
1455+
* @returns {Sequence}
1456+
*/
1457+
const intersperse = curry('intersperse', (seq, e) => pipe(
1458+
seq,
1459+
map(v => [e, v]),
1460+
flat,
1461+
trySkip(1)
1462+
));
1463+
1464+
14421465
/**
14431466
* Forms a sliding window on the underlying iterator.
14441467
*
@@ -1812,6 +1835,7 @@ module.exports = {
18121835
zipLeast2,
18131836
zip2,
18141837
zipLongest2,
1838+
intersperse,
18151839
slidingWindow,
18161840
trySlidingWindow,
18171841
lookahead,

test/sequence.test.js

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ const {
2626
take, takeWhile, takeUntilVal, takeDef, flat, concat, prepend, append,
2727
mapSort, zipLeast, zip, zipLongest, zipLeast2, zip2, zipLongest2,
2828
slidingWindow, trySlidingWindow, lookahead, mod, union, union2,
29-
cartesian, cartesian2,
29+
cartesian, cartesian2, intersperse,
3030
} = require('../src/index');
3131
const { ckEq, ckEqSeq, ckThrows } = require('./util');
3232

@@ -525,3 +525,10 @@ it('union/union2', () => {
525525
ckEq(m2.get('b'), 99);
526526
ckEq(m2.get('x'), 13);
527527
});
528+
529+
it('intersperse', () => {
530+
ckEqSeq(intersperse('', 'x'), '');
531+
ckEqSeq(intersperse('a', 'x'), 'a');
532+
ckEqSeq(intersperse('ab', 'x'), 'axb');
533+
ckEqSeq(intersperse('abc', 'x'), 'axbxc');
534+
});

0 commit comments

Comments
 (0)