@@ -158,6 +158,58 @@ export function join<T = unknown>(...arrays: T[][]): T[] {
158158 return arrays . reduce ( ( a , x ) => a . concat ( x ) , [ ] ) ;
159159}
160160
161+ /** Turn a 2-tuple of lists into a list of 2-tuples. For example: `[['a', 'b', 'c'], [1, 2, 3]]` becomes `[['a', 1], ['b', 2], ['c', 3]]` */
162+ export function zip2 < A , B > ( lists : [ A [ ] , B [ ] ] ) {
163+ return zipAny ( lists ) as Array < [ A , B ] > ;
164+ }
165+
166+ /** Turn a 3-tuple of lists into a list of 3-tuples. */
167+ export function zip3 < A , B , C > ( lists : [ A [ ] , B [ ] , C [ ] ] ) {
168+ return zipAny ( lists ) as Array < [ A , B , C ] > ;
169+ }
170+
171+ /** Turn a 4-tuple of lists into a list of 4-tuples. */
172+ export function zip4 < A , B , C , D > ( lists : [ A [ ] , B [ ] , C [ ] , D [ ] ] ) {
173+ return zipAny ( lists ) as Array < [ A , B , C , D ] > ;
174+ }
175+
176+ /** Turn a n-tuple of lists into a list of n-tuples. */
177+ export function zipAny ( lists : any [ ] [ ] ) {
178+ const zipped = lists [ 0 ] . map ( ( ) => [ ] ) as any [ ] [ ] ;
179+ for ( const [ index , zippedList ] of zipped . entries ( ) ) {
180+ for ( const list of lists ) {
181+ zippedList . push ( list [ index ] ) ;
182+ }
183+ }
184+ return zipped ;
185+ }
186+
187+ /** Turn a list of 2-tuples into a 2-tuple of lists. For example: `[['a', 1], ['b', 2], ['c', 3]]` becomes `[['a', 'b', 'c'], [1, 2, 3]]` */
188+ export function unzip2 < A , B > ( tuples : Array < [ A , B ] > ) {
189+ return unzipAny ( tuples ) as [ A [ ] , B [ ] ] ;
190+ }
191+
192+ /** Turn a list of 3-tuples into a 3-tuple of lists. */
193+ export function unzip3 < A , B , C > ( tuples : Array < [ A , B , C ] > ) {
194+ return unzipAny ( tuples ) as [ A [ ] , B [ ] , C [ ] ] ;
195+ }
196+
197+ /** Turn a list of 4-tuples into a 4-tuple of lists. */
198+ function unzip4 < A , B , C , D > ( tuples : Array < [ A , B , C , D ] > ) {
199+ return unzipAny ( tuples ) as [ A [ ] , B [ ] , C [ ] , D [ ] ] ;
200+ }
201+
202+ /** Turn a list of n-tuples into a n-tuple of lists. */
203+ function unzipAny ( tuples : any [ ] [ ] ) {
204+ const init = tuples . map ( ( ) => [ ] ) as any [ ] [ ] ;
205+ return tuples . reduce (
206+ ( unzipped : any [ ] [ ] , tuple ) => {
207+ return tuple . map ( ( elem , index ) => [ ...unzipped [ index ] , elem ] ) ;
208+ } ,
209+ init
210+ ) ;
211+ }
212+
161213type LinkedListItem < T > = { val : T , prev : LinkedListItem < T > , next : LinkedListItem < T > } ;
162214
163215/** Converts an array to a linked list data structure. */
0 commit comments