@khanacademy/kmath 0.0.0-PR971-20240207180432 → 0.0.0-PR973-20240207194831

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,145 @@
1
+ import * as vector from "../vector";
2
+
3
+ describe("kvector", function () {
4
+ it("vector.zip should return empty given empty", function () {
5
+ expect(vector.zip([], [])).toEqual([]);
6
+ });
7
+
8
+ it("vector.zip should create vectors from x and y coords", function () {
9
+ expect(vector.zip([1, 2], [3, 4])).toEqual([
10
+ [1, 3],
11
+ [2, 4],
12
+ ]);
13
+ });
14
+
15
+ it("vector.zip should ignore extra xs", function () {
16
+ expect(vector.zip([1, 2, 9], [3, 4])).toEqual([
17
+ [1, 3],
18
+ [2, 4],
19
+ ]);
20
+ });
21
+
22
+ it("vector.zip should ignore extra ys", function () {
23
+ expect(vector.zip([1, 2], [3, 4, 9])).toEqual([
24
+ [1, 3],
25
+ [2, 4],
26
+ ]);
27
+ });
28
+
29
+ it("vector.map should transform a 2D vector", function () {
30
+ const double = (x) => x * 2;
31
+ expect(vector.map([3, 4], double)).toEqual([6, 8]);
32
+ });
33
+
34
+ it("vector.map should pass the index of each element to the callback", function () {
35
+ expect(vector.map([3, 4], (_, i) => i)).toEqual([0, 1]);
36
+ });
37
+
38
+ it("vector.add should add two 2D vectors", function () {
39
+ const result = vector.add([1, 2], [3, 4]);
40
+ expect(result).toStrictEqual([4, 6]);
41
+ });
42
+
43
+ it("vector.add should add two 3D vectors", function () {
44
+ const result = vector.add([1, 2, 3], [4, 5, 6]);
45
+ expect(result).toStrictEqual([5, 7, 9]);
46
+ });
47
+
48
+ it("vector.add should add three 2D vectors", function () {
49
+ const result = vector.add([1, 2], [3, 4], [5, 6]);
50
+ expect(result).toStrictEqual([9, 12]);
51
+ });
52
+
53
+ it("vector.subtract should subtract two 2D vectors", function () {
54
+ const result = vector.subtract([1, 2], [3, 4]);
55
+ expect(result).toStrictEqual([-2, -2]);
56
+ });
57
+
58
+ it("vector.subtract should subtract two 3D vectors", function () {
59
+ const result = vector.subtract([1, 2, 3], [4, 5, 6]);
60
+ expect(result).toStrictEqual([-3, -3, -3]);
61
+ });
62
+
63
+ it("vector.dot should take the dot product of 2 2D vectors", function () {
64
+ const result = vector.dot([1, 2], [3, 4]);
65
+ expect(result).toBe(3 + 8);
66
+ });
67
+
68
+ it("vector.dot should take the dot product of 2 3D vectors", function () {
69
+ const result = vector.dot([1, 2, 3], [4, 5, 6]);
70
+ expect(result).toBe(4 + 10 + 18);
71
+ });
72
+
73
+ it("vector.scale should scale a 2D vector", function () {
74
+ const result = vector.scale([4, 2], 0.5);
75
+ expect(result).toStrictEqual([2, 1]);
76
+ });
77
+
78
+ it("vector.scale should scale a 3D vector", function () {
79
+ const result = vector.scale([1, 2, 3], 2);
80
+ expect(result).toStrictEqual([2, 4, 6]);
81
+ });
82
+
83
+ it("vector.length should take the length of a 2D vector", function () {
84
+ const result = vector.length([3, 4]);
85
+ expect(result).toBe(5);
86
+ });
87
+
88
+ it("vector.length should take the length of a 3D vector", function () {
89
+ const result = vector.length([4, 0, 3]);
90
+ expect(result).toBe(5);
91
+ });
92
+
93
+ it("vector.equal should return true on two equal 3D vectors", function () {
94
+ const result = vector.equal([6, 3, 4], [6, 3, 4]);
95
+ expect(result).toBe(true);
96
+ });
97
+
98
+ it("vector.equal should return false on two inequal 3D vectors", function () {
99
+ const result = vector.equal([6, 3, 4], [6, 4, 4]);
100
+ expect(result).toBe(false);
101
+ });
102
+
103
+ it("vector.equal should return false on a 2D and 3D vector", function () {
104
+ const result = vector.equal([6, 4], [6, 4, 4]);
105
+ expect(result).toBe(false);
106
+ });
107
+
108
+ it("vector.equal should return false on a 2D and 3D vector", function () {
109
+ const result = vector.equal([6, 3, 4], [6, 3]);
110
+ expect(result).toBe(false);
111
+ });
112
+
113
+ it("vector.equal should return false on a 2D and 3D vector with a trailing 0", function () {
114
+ const result = vector.equal([6, 3, 0], [6, 3]);
115
+ expect(result).toBe(false);
116
+ });
117
+
118
+ it(
119
+ "vector.collinear should return true on two collinear vectors of " +
120
+ "the same magnitude but different direction",
121
+ function () {
122
+ const result = vector.collinear([3, 3], [-3, -3]);
123
+ expect(result).toBe(true);
124
+ },
125
+ );
126
+
127
+ it(
128
+ "vector.collinear should return true on two collinear vectors of " +
129
+ "different magnitudes",
130
+ function () {
131
+ const result = vector.collinear([2, 1], [6, 3]);
132
+ expect(result).toBe(true);
133
+ },
134
+ );
135
+
136
+ it("vector.collinear should return false on non-collinear vectors", function () {
137
+ const result = vector.collinear([1, 2], [-1, 2]);
138
+ expect(result).toBe(false);
139
+ });
140
+
141
+ it("vector.negate of [-2, 2] is [2, -2]", function () {
142
+ const result = vector.negate([-2, 2]);
143
+ expect(result).toStrictEqual([2, -2]);
144
+ });
145
+ });
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ export {libVersion} from "./version";
2
+
3
+ export * as number from "./number";
4
+ export * as vector from "./vector";
5
+ export * as point from "./point";
6
+ export * as line from "./line";
7
+ export * as ray from "./ray";
package/src/line.ts ADDED
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Line Utils
3
+ * A line is an array of two points e.g. [[-5, 0], [5, 0]].
4
+ */
5
+
6
+ import * as kpoint from "./point";
7
+ import * as kvector from "./vector";
8
+
9
+ import type {Point} from "./point";
10
+
11
+ export type Line = [Point, Point];
12
+
13
+ export function distanceToPoint(line: Line, point: Point): number {
14
+ return kpoint.distanceToLine(point, line);
15
+ }
16
+
17
+ export function reflectPoint(line: Line, point: Point): Point {
18
+ return kpoint.reflectOverLine(point, line);
19
+ }
20
+
21
+ export function midpoint(line: Line): Point {
22
+ return [(line[0][0] + line[1][0]) / 2, (line[0][1] + line[1][1]) / 2];
23
+ }
24
+
25
+ export function equal(line1: Line, line2: Line, tolerance?: number): boolean {
26
+ // TODO: A nicer implementation might just check collinearity of
27
+ // vectors using underscore magick
28
+ // Compare the directions of the lines
29
+ const v1 = kvector.subtract(line1[1], line1[0]);
30
+ const v2 = kvector.subtract(line2[1], line2[0]);
31
+ if (!kvector.collinear(v1, v2, tolerance)) {
32
+ return false;
33
+ }
34
+ // If the start point is the same for the two lines, then they are the same
35
+ if (kpoint.equal(line1[0], line2[0])) {
36
+ return true;
37
+ }
38
+ // Make sure that the direction to get from line1 to
39
+ // line2 is the same as the direction of the lines
40
+ const line1ToLine2Vector = kvector.subtract(line2[0], line1[0]);
41
+ return kvector.collinear(v1, line1ToLine2Vector, tolerance);
42
+ }
package/src/logo.ts ADDED
@@ -0,0 +1,39 @@
1
+ /* eslint-disable import/no-default-export */
2
+ // This file describes the graphie source code of the kmath logo
3
+ // currently used on khan.github.io.
4
+ //
5
+ // Also located at http://ka-perseus-graphie.s3.amazonaws.com/42ef3cbadc3e6464124533191728c3c5c55c7355.svg
6
+
7
+ declare let init: any;
8
+ declare let ellipse: any;
9
+ declare let line: any;
10
+
11
+ const GREEN = "#28AE7B";
12
+
13
+ export default () => {
14
+ init({
15
+ range: [
16
+ [0, 10],
17
+ [0, 10],
18
+ ],
19
+ scale: 40,
20
+ });
21
+
22
+ ellipse(5, 5, 5, {
23
+ stroke: null,
24
+ fill: GREEN,
25
+ });
26
+
27
+ line([2, 5], [8.5, 5], {
28
+ stroke: "WHITE",
29
+ fill: "WHITE",
30
+ strokeWidth: 25,
31
+ arrows: "->",
32
+ });
33
+
34
+ line([5, 2], [5, 8], {
35
+ stroke: "WHITE",
36
+ fill: "WHITE",
37
+ strokeWidth: 25,
38
+ });
39
+ };
package/src/number.ts ADDED
@@ -0,0 +1,104 @@
1
+ /**
2
+ * Number Utils
3
+ * A number is a js-number, e.g. 5.12
4
+ */
5
+
6
+ import _ from "underscore";
7
+
8
+ export const DEFAULT_TOLERANCE = 1e-9;
9
+
10
+ // TODO: Should this just be Number.Epsilon
11
+ export const EPSILON: number = Math.pow(2, -42);
12
+
13
+ export function is(x: any): boolean {
14
+ return _.isNumber(x) && !_.isNaN(x);
15
+ }
16
+
17
+ export function equal(x: number, y: number, tolerance?: number): boolean {
18
+ // Checking for undefined makes this function behave nicely
19
+ // with vectors of different lengths that are _.zip'd together
20
+ if (x == null || y == null) {
21
+ return x === y;
22
+ }
23
+ // We check === here so that +/-Infinity comparisons work correctly
24
+ if (x === y) {
25
+ return true;
26
+ }
27
+ if (tolerance == null) {
28
+ tolerance = DEFAULT_TOLERANCE;
29
+ }
30
+ return Math.abs(x - y) < tolerance;
31
+ }
32
+
33
+ export function sign(
34
+ x: number,
35
+ tolerance?: number,
36
+ ): number /* Should be: 0 | 1 | -1 */ {
37
+ return equal(x, 0, tolerance) ? 0 : Math.abs(x) / x;
38
+ }
39
+
40
+ export function isInteger(num: number, tolerance?: number): boolean {
41
+ return equal(Math.round(num), num, tolerance);
42
+ }
43
+
44
+ // Round a number to a certain number of decimal places
45
+ export function round(num: number, precision: number): number {
46
+ const factor = Math.pow(10, precision);
47
+ return Math.round(num * factor) / factor;
48
+ }
49
+
50
+ // Round num to the nearest multiple of increment
51
+ // i.e. roundTo(83, 5) -> 85
52
+ export function roundTo(num: number, increment: number): number {
53
+ return Math.round(num / increment) * increment;
54
+ }
55
+
56
+ export function floorTo(num: number, increment: number): number {
57
+ return Math.floor(num / increment) * increment;
58
+ }
59
+
60
+ export function ceilTo(num: number, increment: number): number {
61
+ return Math.ceil(num / increment) * increment;
62
+ }
63
+
64
+ /**
65
+ * toFraction
66
+ *
67
+ * Returns a [numerator, denominator] array rational representation
68
+ * of `decimal`
69
+ *
70
+ * See http://en.wikipedia.org/wiki/Continued_fraction for implementation
71
+ * details
72
+ *
73
+ * toFraction(4/8) => [1, 2]
74
+ * toFraction(0.66) => [33, 50]
75
+ * toFraction(0.66, 0.01) => [2/3]
76
+ * toFraction(283 + 1/3) => [850, 3]
77
+ */
78
+ export function toFraction(
79
+ decimal: number,
80
+ // can't be 0
81
+ tolerance: number = EPSILON,
82
+ maxDenominator = 1000,
83
+ ): [number, number] {
84
+ // Initialize everything to compute successive terms of
85
+ // continued-fraction approximations via recurrence relation
86
+ let n = [1, 0];
87
+ let d = [0, 1];
88
+ let a = Math.floor(decimal);
89
+ let rem = decimal - a;
90
+
91
+ while (d[0] <= maxDenominator) {
92
+ if (equal(n[0] / d[0], decimal, tolerance)) {
93
+ return [n[0], d[0]];
94
+ }
95
+ n = [a * n[0] + n[1], n[0]];
96
+ d = [a * d[0] + d[1], d[0]];
97
+ a = Math.floor(1 / rem);
98
+ rem = 1 / rem - a;
99
+ }
100
+
101
+ // We failed to find a nice rational representation,
102
+ // so return an irrational "fraction"
103
+ return [decimal, 1];
104
+ }
package/src/point.ts ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Point Utils
3
+ * A point is an array of two numbers e.g. [0, 0].
4
+ */
5
+
6
+ import * as knumber from "./number";
7
+ import * as kvector from "./vector";
8
+
9
+ // A point, in 2D, 3D, or nD space.
10
+ export type Point = ReadonlyArray<number>;
11
+
12
+ // Rotate point (around origin unless a center is specified)
13
+ export function rotateRad(point: Point, theta: number, center?: Point): Point {
14
+ if (center === undefined) {
15
+ return kvector.rotateRad(point, theta);
16
+ } else {
17
+ return kvector.add(
18
+ center,
19
+ kvector.rotateRad(kvector.subtract(point, center), theta),
20
+ );
21
+ }
22
+ }
23
+
24
+ export function rotateDeg(point: Point, theta: number, center?: Point): Point {
25
+ if (center === undefined) {
26
+ return kvector.rotateDeg(point, theta);
27
+ } else {
28
+ return kvector.add(
29
+ center,
30
+ kvector.rotateDeg(kvector.subtract(point, center), theta),
31
+ );
32
+ }
33
+ }
34
+
35
+ // Distance between two points
36
+ export function distanceToPoint(point1: Point, point2: Point): number {
37
+ return kvector.length(kvector.subtract(point1, point2));
38
+ }
39
+
40
+ // Distance between point and line
41
+ export function distanceToLine(point: Point, line: [Point, Point]): number {
42
+ const lv = kvector.subtract(line[1], line[0]);
43
+ const pv = kvector.subtract(point, line[0]);
44
+ const projectedPv = kvector.projection(pv, lv);
45
+ const distancePv = kvector.subtract(projectedPv, pv);
46
+ return kvector.length(distancePv);
47
+ }
48
+
49
+ // Reflect point over line
50
+ export function reflectOverLine<P extends Point>(point: P, line: [P, P]): P {
51
+ const lv = kvector.subtract(line[1], line[0]);
52
+ const pv = kvector.subtract(point, line[0]);
53
+ const projectedPv = kvector.projection(pv, lv);
54
+ const reflectedPv = kvector.subtract(kvector.scale(projectedPv, 2), pv);
55
+ return kvector.add(line[0], reflectedPv);
56
+ }
57
+
58
+ /**
59
+ * Compares two points, returning -1, 0, or 1, for use with
60
+ * Array.prototype.sort
61
+ *
62
+ * Note: This technically doesn't satisfy the total-ordering
63
+ * requirements of Array.prototype.sort unless equalityTolerance
64
+ * is 0. In some cases very close points that compare within a
65
+ * few equalityTolerances could appear in the wrong order.
66
+ */
67
+ export function compare(
68
+ point1: Point,
69
+ point2: Point,
70
+ equalityTolerance?: number,
71
+ ): number /* TODO: convert to -1 | 0 | 1 type */ {
72
+ if (point1.length !== point2.length) {
73
+ return point1.length - point2.length;
74
+ }
75
+ for (let i = 0; i < point1.length; i++) {
76
+ if (!knumber.equal(point1[i], point2[i], equalityTolerance)) {
77
+ return point1[i] - point2[i];
78
+ }
79
+ }
80
+ return 0;
81
+ }
82
+
83
+ // Check if a value is a point
84
+ export const is = kvector.is;
85
+
86
+ // Add and subtract vector(s)
87
+ export const addVector = kvector.add;
88
+ export const addVectors = kvector.add;
89
+ export const subtractVector = kvector.subtract;
90
+ export const equal = kvector.equal;
91
+
92
+ // Convert from cartesian to polar and back
93
+ export const polarRadFromCart = kvector.polarRadFromCart;
94
+ export const polarDegFromCart = kvector.polarDegFromCart;
95
+ export const cartFromPolarRad = kvector.cartFromPolarRad;
96
+ export const cartFromPolarDeg = kvector.cartFromPolarDeg;
97
+
98
+ // Rounding
99
+ export const round = kvector.round;
100
+ export const roundTo = kvector.roundTo;
101
+ export const floorTo = kvector.floorTo;
102
+ export const ceilTo = kvector.ceilTo;
package/src/ray.ts ADDED
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Ray Utils
3
+ * A ray (→) is an array of an endpoint and another point along the ray.
4
+ * For example, [[0, 0], [1, 0]] is the ray starting at the origin and
5
+ * traveling along the positive x-axis.
6
+ */
7
+
8
+ import * as kpoint from "./point";
9
+ import * as kvector from "./vector";
10
+
11
+ import type {Point} from "./point";
12
+
13
+ export type Ray = [Point, Point];
14
+
15
+ export function equal(ray1: Ray, ray2: Ray, tolerance?: number): boolean {
16
+ // Compare the directions of the rays
17
+ const v1 = kvector.subtract(ray1[1], ray1[0]);
18
+ const v2 = kvector.subtract(ray2[1], ray2[0]);
19
+
20
+ const sameOrigin = kpoint.equal(ray1[0], ray2[0]);
21
+ const codirectional = kvector.codirectional(v1, v2, tolerance);
22
+
23
+ return sameOrigin && codirectional;
24
+ }