Haskell's list.transpose in TypeScript

How to use

Install via yarn add locutus and import: import { transpose } from 'locutus/haskell/list/transpose'.

Or with CommonJS: const { transpose } = require('locutus/haskell/list/transpose')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1transpose([[1, 2, 3], [4, 5, 6]])[[1, 4], [2, 5], [3, 6]]
2transpose([['a', 'b'], ['c'], ['d', 'e', 'f']])[['a', 'c', 'd'], ['b', 'e'], ['f']]
3transpose([])[]

Notes

  • Transposes rows and columns, dropping exhausted rows like Haskell Data.List.transpose.

Here's what our current TypeScript equivalent to Haskell's list.transpose looks like.

export function transpose<T>(rows: Array<Array<T> | unknown> | unknown): T[][] {
// discuss at: https://locutus.io/haskell/list/transpose/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Transposes rows and columns, dropping exhausted rows like Haskell Data.List.transpose.
// example 1: transpose([[1, 2, 3], [4, 5, 6]])
// returns 1: [[1, 4], [2, 5], [3, 6]]
// example 2: transpose([['a', 'b'], ['c'], ['d', 'e', 'f']])
// returns 2: [['a', 'c', 'd'], ['b', 'e'], ['f']]
// example 3: transpose([])
// returns 3: []

if (!Array.isArray(rows)) {
return []
}

const queue = rows
.filter((row): row is T[] => Array.isArray(row))
.map((row) => row.slice())
.filter((row) => row.length > 0)

const out: T[][] = []
while (queue.length > 0) {
const column: T[] = []
for (let i = queue.length - 1; i >= 0; i--) {
const row = queue[i]
const head = row?.shift()
if (typeof head !== 'undefined') {
column.push(head)
}
if (!row || row.length === 0) {
queue.splice(i, 1)
}
}
column.reverse()
out.push(column)
}

return out
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 2 Haskell functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Haskell base Data.List docs.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.


« More Haskell list functions


Star