generated from fauna-labs/fauna-labs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dotProduct.ts
73 lines (70 loc) · 1.59 KB
/
dotProduct.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
// Copyright Fauna, Inc.
// SPDX-License-Identifier: MIT-0
import faunadb, { CreateFunction } from 'faunadb';
const q = faunadb.query
const {
Add,
Call,
Lambda,
Multiply,
Query,
Reduce,
Select,
Var
} = q;
/**
* DotProduct() accepts two arrays of equal length representing vectors and
* returns the dot product or scalar product of those vectors.
* @param {Array<number>} a - The first vector.
* @param {Array<number>} b - The second vector. `b` must be the same length as `a`.
* @returns {number} The dot product of the two vectors.
* Dependencies:
* * [`Tail()`](../collections/tail.ts)
* ```js
* import { Tail } from '@fauna-labs/fql-utilities/collections';
* export default Tail();
* ```
* * [`Zip()`](../collections/zip.ts)
* ```js
* import { Zip } from '@fauna-labs/fql-utilities/collections';
* export default Zip();
* ```
*
* Usage in Fauna Schema Migrate:
* ```js
* import { DotProduct } from '@fauna-labs/fql-utilities/vector';
* export default DotProduct();
* ```
*
* Usage in FQL:
* ```fql
* Let(
* {
* a: [0, 1, 2],
* b: [3, 4, 5]
* },
* Equals(Call("DotProduct", Var("a"), Var("b")), 14) // true
* )
* ```
*/
export function DotProduct(): faunadb.Expr {
return CreateFunction({
name: "DotProduct",
body: Query(
Lambda(
["a", "b"],
Reduce(
Lambda(
["acc", "tuple"],
Add(
Var("acc"),
Multiply(Select(0, Var("tuple")), Select(1, Var("tuple")))
)
),
0,
Call("Zip", [Var("a"), Var("b")])
)
)
)
});
}