Skip to content

Commit

Permalink
Merge pull request #26 from giraugh/feat/intersperse-array
Browse files Browse the repository at this point in the history
`intersperseArray` utility
  • Loading branch information
giraugh authored Jul 19, 2023
2 parents e23cc9d + bb5cff8 commit 6e4f75b
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .changeset/good-terms-deliver.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@giraugh/tools": minor
---

Implement intersperseArray utility
44 changes: 44 additions & 0 deletions lib/arrays/intersperseArray.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Intersperse a seperator element between every element of a given array
* @param arr the array to intersperse into
* @param sep a seperator element to distribute throughout `arr`
* @returns `arr` with `sep` interspersed between every pair of elements
*
* @example
* intersperseArray([[1, 2], [3, 4], [5, 6]], []) // [[1, 2], [], [3, 4], [], [5, 6]]
* @example
* intersperseArray(['alpha', 'beta', 'gamma'], '!') // ['alpha', '!', 'beta', '!', 'gamma']
*/
export const intersperseArray = <T>(arr: T[], sep: T): T[] => {
const gen = function*() {
while (arr.length > 0) {
yield arr.shift()!
if (arr.length > 0) yield sep
}
}
return Array.from(gen())
}


if (import.meta.vitest) {
const { expect, it } = import.meta.vitest

it('works for example 1', () => {
const inter = intersperseArray([[1, 2, 3], [4, 5, 6], [7, 8, 9]], [])
expect(inter).toEqual([[1, 2, 3], [], [4, 5, 6], [], [7, 8, 9]])
})

it('works for example 2', () => {
const inter = intersperseArray(['alpha', 'beta', 'gamma'], '!')
expect(inter).toEqual(['alpha', '!', 'beta', '!', 'gamma'])
})

it('does nothing to an empty array', () => {
expect(intersperseArray([] as string[], 'hello')).toEqual([])
})

it('does nothing to an array with one element', () => {
expect(intersperseArray(['suave'], '$')).toEqual(['suave'])
})
}

0 comments on commit 6e4f75b

Please sign in to comment.