generated from fauna-labs/fauna-labs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
zip.ts
95 lines (92 loc) · 2.36 KB
/
zip.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright Fauna, Inc.
// SPDX-License-Identifier: MIT-0
import faunadb, { CreateFunction } from 'faunadb'
const q = faunadb.query
const {
Abort,
And,
Append,
Call,
Count,
Equals,
GTE,
If,
IsArray,
Lambda,
Let,
Query,
Select,
Subtract,
Var
} = q
/**
* Zip() accepts two arrays of equal length and returns a new array of the same length
* where each element of the new array is a tuple containing the corresponding element
* from the first and the second arguments.
*
* @param {Array<any>} array1 - The first array to zip.
* @param {Array<any>} array2 - The second array to zip. `array2` must be the same length as `array1`.
* @returns {Array<any>} A new array of tuples where each element contains the corresponding element from `array1` and `array2`.
*
* ### Consumes per call
* * 0 Read Ops
* * 0 Write Ops
* * 1 ComputeOp ( FQL verbs total, including 19 FQL verbs each for two Tail calls)
*
* ### Dependencies:
* * [`Tail()`](./tail.ts)
* ```js
* import { Tail } from '@fauna-labs/fql-utilities/collections';
* export default Tail();
* ```
*
* ### Usage in Fauna Schema Migrate:
* ```js
* import { Zip } from '@fauna-labs/fql-utilities/collections';
* export default Zip();
* ```
*
* ### Usage in FQL:
* ```fql
* Let(
* { zippedArray: Call("Zip", Var("array1"), Var("array2")) },
* Equals(Count(Var("zippedArray")), Count(Var("array1"))) // true
* )
* ```
*/
export function Zip(): faunadb.Expr {
return CreateFunction({
name: 'Zip',
body: Query(
Lambda(
["array1", "array2"],
If(
And(
IsArray(Var("array1")),
IsArray(Var("array2")),
Equals(Count(Var("array1")), Count(Var("array2"))),
GTE(Count(Var("array1")), 1)
),
Let(
{
tuple: [[Select(0, Var("array1")), Select(0, Var("array2"))]],
tail_length: Subtract(Count(Var("array1")), 1)
},
If(
Equals(Var("tail_length"), 0),
Var("tuple"),
Append(
Call("Zip", [
Call("Tail", [Var("array1")]),
Call("Tail", [Var("array2")])
]),
Var("tuple")
)
)
),
Abort("Zip requires two arguments that are arrays of the same length.")
)
)
)
})
}