@khanacademy/kmath 1.0.0 → 2.0.0

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,1138 @@
1
+ import { addLibraryVersionToPerseusDebug } from '@khanacademy/perseus-utils';
2
+ import _ from 'underscore';
3
+ import { approximateEqual, approximateDeepEqual } from '@khanacademy/perseus-core';
4
+ import $ from 'jquery';
5
+
6
+ // This file is processed by a Rollup plugin (replace) to inject the production
7
+ // version number during the release build.
8
+ // In dev, you'll never see the version number.
9
+
10
+ const libName = "@khanacademy/kmath";
11
+ const libVersion = "2.0.0";
12
+ addLibraryVersionToPerseusDebug(libName, libVersion);
13
+
14
+ /**
15
+ * Number Utils
16
+ * A number is a js-number, e.g. 5.12
17
+ */
18
+
19
+ const DEFAULT_TOLERANCE = 1e-9;
20
+
21
+ // TODO: Should this just be Number.Epsilon
22
+ const EPSILON = Math.pow(2, -42);
23
+ function is$2(x) {
24
+ return _.isNumber(x) && !_.isNaN(x);
25
+ }
26
+ function equal$4(x, y, tolerance) {
27
+ // Checking for undefined makes this function behave nicely
28
+ // with vectors of different lengths that are _.zip'd together
29
+ if (x == null || y == null) {
30
+ return x === y;
31
+ }
32
+ // We check === here so that +/-Infinity comparisons work correctly
33
+ if (x === y) {
34
+ return true;
35
+ }
36
+ if (tolerance == null) {
37
+ tolerance = DEFAULT_TOLERANCE;
38
+ }
39
+ return Math.abs(x - y) < tolerance;
40
+ }
41
+ function sign$1(x, tolerance) /* Should be: 0 | 1 | -1 */{
42
+ return equal$4(x, 0, tolerance) ? 0 : Math.abs(x) / x;
43
+ }
44
+ function isInteger(num, tolerance) {
45
+ return equal$4(Math.round(num), num, tolerance);
46
+ }
47
+
48
+ // Round a number to a certain number of decimal places
49
+ function round$2(num, precision) {
50
+ const factor = Math.pow(10, precision);
51
+ return Math.round(num * factor) / factor;
52
+ }
53
+
54
+ // Round num to the nearest multiple of increment
55
+ // i.e. roundTo(83, 5) -> 85
56
+ function roundTo$2(num, increment) {
57
+ return Math.round(num / increment) * increment;
58
+ }
59
+ function floorTo$2(num, increment) {
60
+ return Math.floor(num / increment) * increment;
61
+ }
62
+ function ceilTo$2(num, increment) {
63
+ return Math.ceil(num / increment) * increment;
64
+ }
65
+
66
+ /**
67
+ * toFraction
68
+ *
69
+ * Returns a [numerator, denominator] array rational representation
70
+ * of `decimal`
71
+ *
72
+ * See http://en.wikipedia.org/wiki/Continued_fraction for implementation
73
+ * details
74
+ *
75
+ * toFraction(4/8) => [1, 2]
76
+ * toFraction(0.66) => [33, 50]
77
+ * toFraction(0.66, 0.01) => [2/3]
78
+ * toFraction(283 + 1/3) => [850, 3]
79
+ */
80
+ function toFraction(decimal,
81
+ // can't be 0
82
+ tolerance = EPSILON, maxDenominator = 1000) {
83
+ // Initialize everything to compute successive terms of
84
+ // continued-fraction approximations via recurrence relation
85
+ let n = [1, 0];
86
+ let d = [0, 1];
87
+ let a = Math.floor(decimal);
88
+ let rem = decimal - a;
89
+ while (d[0] <= maxDenominator) {
90
+ if (equal$4(n[0] / d[0], decimal, tolerance)) {
91
+ return [n[0], d[0]];
92
+ }
93
+ n = [a * n[0] + n[1], n[0]];
94
+ d = [a * d[0] + d[1], d[0]];
95
+ a = Math.floor(1 / rem);
96
+ rem = 1 / rem - a;
97
+ }
98
+
99
+ // We failed to find a nice rational representation,
100
+ // so return an irrational "fraction"
101
+ return [decimal, 1];
102
+ }
103
+
104
+ var number = /*#__PURE__*/Object.freeze({
105
+ __proto__: null,
106
+ DEFAULT_TOLERANCE: DEFAULT_TOLERANCE,
107
+ EPSILON: EPSILON,
108
+ ceilTo: ceilTo$2,
109
+ equal: equal$4,
110
+ floorTo: floorTo$2,
111
+ is: is$2,
112
+ isInteger: isInteger,
113
+ round: round$2,
114
+ roundTo: roundTo$2,
115
+ sign: sign$1,
116
+ toFraction: toFraction
117
+ });
118
+
119
+ /**
120
+ * Vector Utils
121
+ * A vector is an array of numbers e.g. [0, 3, 4].
122
+ */
123
+
124
+ function arraySum(array) {
125
+ return array.reduce((memo, arg) => memo + arg, 0);
126
+ }
127
+ function arrayProduct(array) {
128
+ return array.reduce((memo, arg) => memo * arg, 1);
129
+ }
130
+ function zip(...arrays) {
131
+ const n = Math.min(...arrays.map(a => a.length));
132
+ const results = [];
133
+ for (let i = 0; i < n; i++) {
134
+ results.push(arrays.map(a => a[i]));
135
+ }
136
+ return results;
137
+ }
138
+ function map(pair, f) {
139
+ return [f(pair[0], 0), f(pair[1], 1)];
140
+ }
141
+
142
+ /**
143
+ * Checks if the given vector contains only numbers and, optionally, is of the
144
+ * right dimension (length).
145
+ *
146
+ * is([1, 2, 3]) -> true
147
+ * is([1, "Hello", 3]) -> false
148
+ * is([1, 2, 3], 1) -> false
149
+ */
150
+
151
+ function is$1(vec, dimension) {
152
+ if (!Array.isArray(vec)) {
153
+ return false;
154
+ }
155
+ if (dimension !== undefined && vec.length !== dimension) {
156
+ return false;
157
+ }
158
+ return vec.every(is$2);
159
+ }
160
+
161
+ // Normalize to a unit vector
162
+ function normalize(v) {
163
+ return scale(v, 1 / length(v));
164
+ }
165
+
166
+ // Length/magnitude of a vector
167
+ function length(v) {
168
+ return Math.sqrt(dot(v, v));
169
+ }
170
+ // Dot product of two vectors
171
+ function dot(a, b) {
172
+ const zipped = zip(a, b);
173
+ const multiplied = zipped.map(arrayProduct);
174
+ return arraySum(multiplied);
175
+ }
176
+
177
+ /* vector-add multiple [x, y] coords/vectors
178
+ *
179
+ * add([1, 2], [3, 4]) -> [4, 6]
180
+ */
181
+ function add$1(...vecs) {
182
+ const zipped = zip(...vecs);
183
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
184
+ return zipped.map(arraySum);
185
+ }
186
+ function subtract(v1, v2) {
187
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
188
+ return zip(v1, v2).map(dim => dim[0] - dim[1]);
189
+ }
190
+ function negate(v) {
191
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
192
+ return v.map(x => {
193
+ return -x;
194
+ });
195
+ }
196
+
197
+ // Scale a vector
198
+ function scale(v1, scalar) {
199
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
200
+ return v1.map(x => {
201
+ return x * scalar;
202
+ });
203
+ }
204
+ function equal$3(v1, v2, tolerance) {
205
+ return v1.length === v2.length && zip(v1, v2).every(pair => equal$4(pair[0], pair[1], tolerance));
206
+ }
207
+ function codirectional(v1, v2, tolerance) {
208
+ // The origin is trivially codirectional with all other vectors.
209
+ // This gives nice semantics for codirectionality between points when
210
+ // comparing their difference vectors.
211
+ if (equal$4(length(v1), 0, tolerance) || equal$4(length(v2), 0, tolerance)) {
212
+ return true;
213
+ }
214
+ v1 = normalize(v1);
215
+ v2 = normalize(v2);
216
+ return equal$3(v1, v2, tolerance);
217
+ }
218
+ function collinear$1(v1, v2, tolerance) {
219
+ return codirectional(v1, v2, tolerance) || codirectional(v1, negate(v2), tolerance);
220
+ }
221
+
222
+ // TODO(jeremy) These coordinate conversion functions really only handle 2D points (ie. [number, number])
223
+
224
+ // Convert a cartesian coordinate into a radian polar coordinate
225
+ function polarRadFromCart$1(v) {
226
+ const radius = length(v);
227
+ let theta = Math.atan2(v[1], v[0]);
228
+
229
+ // Convert angle range from [-pi, pi] to [0, 2pi]
230
+ if (theta < 0) {
231
+ theta += 2 * Math.PI;
232
+ }
233
+ return [radius, theta];
234
+ }
235
+
236
+ // Converts a cartesian coordinate into a degree polar coordinate
237
+ function polarDegFromCart$1(v) /* TODO: convert to tuple/Point */{
238
+ const polar = polarRadFromCart$1(v);
239
+ return [polar[0], polar[1] * 180 / Math.PI];
240
+ }
241
+
242
+ /* Convert a polar coordinate into a cartesian coordinate
243
+ *
244
+ * Examples:
245
+ * cartFromPolarRad(5, Math.PI)
246
+ */
247
+ function cartFromPolarRad$1(radius, theta = 0) /* TODO: convert to tuple/Point */{
248
+ return [radius * Math.cos(theta), radius * Math.sin(theta)];
249
+ }
250
+
251
+ /* Convert a polar coordinate into a cartesian coordinate
252
+ *
253
+ * Examples:
254
+ * cartFromPolarDeg(5, 30)
255
+ */
256
+ function cartFromPolarDeg$1(radius, theta = 0) {
257
+ return cartFromPolarRad$1(radius, theta * Math.PI / 180);
258
+ }
259
+
260
+ // Rotate vector
261
+ function rotateRad$1(v, theta) {
262
+ const polar = polarRadFromCart$1(v);
263
+ const angle = polar[1] + theta;
264
+ return cartFromPolarRad$1(polar[0], angle);
265
+ }
266
+ function rotateDeg$1(v, theta) {
267
+ const polar = polarDegFromCart$1(v);
268
+ const angle = polar[1] + theta;
269
+ return cartFromPolarDeg$1(polar[0], angle);
270
+ }
271
+
272
+ // Angle between two vectors
273
+ function angleRad(v1, v2) {
274
+ return Math.acos(dot(v1, v2) / (length(v1) * length(v2)));
275
+ }
276
+ function angleDeg(v1, v2) {
277
+ return angleRad(v1, v2) * 180 / Math.PI;
278
+ }
279
+
280
+ // Vector projection of v1 onto v2
281
+ function projection(v1, v2) {
282
+ const scalar = dot(v1, v2) / dot(v2, v2);
283
+ return scale(v2, scalar);
284
+ }
285
+
286
+ // Round each number to a certain number of decimal places
287
+ function round$1(vec, precision) {
288
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
289
+ return vec.map((elem, i) => round$2(elem, precision[i] || precision));
290
+ }
291
+
292
+ // Round each number to the nearest increment
293
+
294
+ function roundTo$1(vec, increment) {
295
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
296
+ return vec.map((elem, i) => roundTo$2(elem, increment[i] || increment));
297
+ }
298
+ function floorTo$1(vec, increment) {
299
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
300
+ return vec.map((elem, i) => floorTo$2(elem, increment[i] || increment));
301
+ }
302
+ function ceilTo$1(vec, increment) {
303
+ // @ts-expect-error - TS2322 - Type 'number[]' is not assignable to type 'V'.
304
+ return vec.map((elem, i) => ceilTo$2(elem, increment[i] || increment));
305
+ }
306
+
307
+ var vector$1 = /*#__PURE__*/Object.freeze({
308
+ __proto__: null,
309
+ add: add$1,
310
+ angleDeg: angleDeg,
311
+ angleRad: angleRad,
312
+ cartFromPolarDeg: cartFromPolarDeg$1,
313
+ cartFromPolarRad: cartFromPolarRad$1,
314
+ ceilTo: ceilTo$1,
315
+ codirectional: codirectional,
316
+ collinear: collinear$1,
317
+ dot: dot,
318
+ equal: equal$3,
319
+ floorTo: floorTo$1,
320
+ is: is$1,
321
+ length: length,
322
+ map: map,
323
+ negate: negate,
324
+ normalize: normalize,
325
+ polarDegFromCart: polarDegFromCart$1,
326
+ polarRadFromCart: polarRadFromCart$1,
327
+ projection: projection,
328
+ rotateDeg: rotateDeg$1,
329
+ rotateRad: rotateRad$1,
330
+ round: round$1,
331
+ roundTo: roundTo$1,
332
+ scale: scale,
333
+ subtract: subtract,
334
+ zip: zip
335
+ });
336
+
337
+ /**
338
+ * Point Utils
339
+ * A point is an array of two numbers e.g. [0, 0].
340
+ */
341
+
342
+
343
+ // A point, in 2D, 3D, or nD space.
344
+
345
+ // Rotate point (around origin unless a center is specified)
346
+ function rotateRad(point, theta, center) {
347
+ if (center === undefined) {
348
+ return rotateRad$1(point, theta);
349
+ } else {
350
+ return add$1(center, rotateRad$1(subtract(point, center), theta));
351
+ }
352
+ }
353
+ function rotateDeg(point, theta, center) {
354
+ if (center === undefined) {
355
+ return rotateDeg$1(point, theta);
356
+ } else {
357
+ return add$1(center, rotateDeg$1(subtract(point, center), theta));
358
+ }
359
+ }
360
+
361
+ // Distance between two points
362
+ function distanceToPoint$1(point1, point2) {
363
+ return length(subtract(point1, point2));
364
+ }
365
+
366
+ // Distance between point and line
367
+ function distanceToLine(point, line) {
368
+ const lv = subtract(line[1], line[0]);
369
+ const pv = subtract(point, line[0]);
370
+ const projectedPv = projection(pv, lv);
371
+ const distancePv = subtract(projectedPv, pv);
372
+ return length(distancePv);
373
+ }
374
+
375
+ // Reflect point over line
376
+ function reflectOverLine(point, line) {
377
+ const lv = subtract(line[1], line[0]);
378
+ const pv = subtract(point, line[0]);
379
+ const projectedPv = projection(pv, lv);
380
+ const reflectedPv = subtract(scale(projectedPv, 2), pv);
381
+ return add$1(line[0], reflectedPv);
382
+ }
383
+
384
+ /**
385
+ * Compares two points, returning -1, 0, or 1, for use with
386
+ * Array.prototype.sort
387
+ *
388
+ * Note: This technically doesn't satisfy the total-ordering
389
+ * requirements of Array.prototype.sort unless equalityTolerance
390
+ * is 0. In some cases very close points that compare within a
391
+ * few equalityTolerances could appear in the wrong order.
392
+ */
393
+ function compare(point1, point2, equalityTolerance) /* TODO: convert to -1 | 0 | 1 type */{
394
+ if (point1.length !== point2.length) {
395
+ return point1.length - point2.length;
396
+ }
397
+ for (let i = 0; i < point1.length; i++) {
398
+ if (!equal$4(point1[i], point2[i], equalityTolerance)) {
399
+ return point1[i] - point2[i];
400
+ }
401
+ }
402
+ return 0;
403
+ }
404
+
405
+ // Check if a value is a point
406
+ const is = is$1;
407
+
408
+ // Add and subtract vector(s)
409
+ const addVector = add$1;
410
+ const addVectors = add$1;
411
+ const subtractVector = subtract;
412
+ const equal$2 = equal$3;
413
+
414
+ // Convert from cartesian to polar and back
415
+ const polarRadFromCart = polarRadFromCart$1;
416
+ const polarDegFromCart = polarDegFromCart$1;
417
+ const cartFromPolarRad = cartFromPolarRad$1;
418
+ const cartFromPolarDeg = cartFromPolarDeg$1;
419
+
420
+ // Rounding
421
+ const round = round$1;
422
+ const roundTo = roundTo$1;
423
+ const floorTo = floorTo$1;
424
+ const ceilTo = ceilTo$1;
425
+
426
+ var point = /*#__PURE__*/Object.freeze({
427
+ __proto__: null,
428
+ addVector: addVector,
429
+ addVectors: addVectors,
430
+ cartFromPolarDeg: cartFromPolarDeg,
431
+ cartFromPolarRad: cartFromPolarRad,
432
+ ceilTo: ceilTo,
433
+ compare: compare,
434
+ distanceToLine: distanceToLine,
435
+ distanceToPoint: distanceToPoint$1,
436
+ equal: equal$2,
437
+ floorTo: floorTo,
438
+ is: is,
439
+ polarDegFromCart: polarDegFromCart,
440
+ polarRadFromCart: polarRadFromCart,
441
+ reflectOverLine: reflectOverLine,
442
+ rotateDeg: rotateDeg,
443
+ rotateRad: rotateRad,
444
+ round: round,
445
+ roundTo: roundTo,
446
+ subtractVector: subtractVector
447
+ });
448
+
449
+ /**
450
+ * Line Utils
451
+ * A line is an array of two points e.g. [[-5, 0], [5, 0]].
452
+ */
453
+
454
+ function distanceToPoint(line, point$1) {
455
+ return distanceToLine(point$1, line);
456
+ }
457
+ function reflectPoint(line, point$1) {
458
+ return reflectOverLine(point$1, line);
459
+ }
460
+ function midpoint(line) {
461
+ return [(line[0][0] + line[1][0]) / 2, (line[0][1] + line[1][1]) / 2];
462
+ }
463
+ function equal$1(line1, line2, tolerance) {
464
+ // TODO: A nicer implementation might just check collinearity of
465
+ // vectors using underscore magick
466
+ // Compare the directions of the lines
467
+ const v1 = subtract(line1[1], line1[0]);
468
+ const v2 = subtract(line2[1], line2[0]);
469
+ if (!collinear$1(v1, v2, tolerance)) {
470
+ return false;
471
+ }
472
+ // If the start point is the same for the two lines, then they are the same
473
+ if (equal$2(line1[0], line2[0])) {
474
+ return true;
475
+ }
476
+ // Make sure that the direction to get from line1 to
477
+ // line2 is the same as the direction of the lines
478
+ const line1ToLine2Vector = subtract(line2[0], line1[0]);
479
+ return collinear$1(v1, line1ToLine2Vector, tolerance);
480
+ }
481
+
482
+ var line = /*#__PURE__*/Object.freeze({
483
+ __proto__: null,
484
+ distanceToPoint: distanceToPoint,
485
+ equal: equal$1,
486
+ midpoint: midpoint,
487
+ reflectPoint: reflectPoint
488
+ });
489
+
490
+ /**
491
+ * Ray Utils
492
+ * A ray (→) is an array of an endpoint and another point along the ray.
493
+ * For example, [[0, 0], [1, 0]] is the ray starting at the origin and
494
+ * traveling along the positive x-axis.
495
+ */
496
+
497
+ function equal(ray1, ray2, tolerance) {
498
+ // Compare the directions of the rays
499
+ const v1 = subtract(ray1[1], ray1[0]);
500
+ const v2 = subtract(ray2[1], ray2[0]);
501
+ const sameOrigin = equal$2(ray1[0], ray2[0]);
502
+ const codirectional$1 = codirectional(v1, v2, tolerance);
503
+ return sameOrigin && codirectional$1;
504
+ }
505
+
506
+ var ray = /*#__PURE__*/Object.freeze({
507
+ __proto__: null,
508
+ equal: equal
509
+ });
510
+
511
+ const KhanMath = {
512
+ // Simplify formulas before display
513
+ cleanMath: function (expr) {
514
+ return typeof expr === "string" ? expr.replace(/\+\s*-/g, "- ").replace(/-\s*-/g, "+ ").replace(/\^1/g, "") : expr;
515
+ },
516
+ // Bound a number by 1e-6 and 1e20 to avoid exponents after toString
517
+ bound: function (num) {
518
+ if (num === 0) {
519
+ return num;
520
+ }
521
+ if (num < 0) {
522
+ return -KhanMath.bound(-num);
523
+ }
524
+ return Math.max(1e-6, Math.min(num, 1e20));
525
+ },
526
+ factorial: function (x) {
527
+ if (x <= 1) {
528
+ return x;
529
+ }
530
+ return x * KhanMath.factorial(x - 1);
531
+ },
532
+ getGCD: function (a, b) {
533
+ if (arguments.length > 2) {
534
+ // TODO(kevinb): rewrite using rest args instead of arguments
535
+ // eslint-disable-next-line prefer-rest-params
536
+ const rest = [].slice.call(arguments, 1);
537
+ // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
538
+ return KhanMath.getGCD(a, KhanMath.getGCD(...rest));
539
+ }
540
+ let mod;
541
+ a = Math.abs(a);
542
+ b = Math.abs(b);
543
+
544
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
545
+ while (b) {
546
+ mod = a % b;
547
+ a = b;
548
+ b = mod;
549
+ }
550
+ return a;
551
+ },
552
+ getLCM: function (a, b) {
553
+ if (arguments.length > 2) {
554
+ // TODO(kevinb): rewrite using rest args instead of arguments
555
+ // eslint-disable-next-line prefer-rest-params
556
+ const rest = [].slice.call(arguments, 1);
557
+ // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
558
+ return KhanMath.getLCM(a, KhanMath.getLCM(...rest));
559
+ }
560
+ return Math.abs(a * b) / KhanMath.getGCD(a, b);
561
+ },
562
+ primes: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97],
563
+ isPrime: function (n) {
564
+ if (n <= 1) {
565
+ return false;
566
+ }
567
+ if (n < 101) {
568
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
569
+ return !!$.grep(KhanMath.primes, function (p, i) {
570
+ return Math.abs(p - n) <= 0.5;
571
+ }).length;
572
+ }
573
+ if (n <= 1 || n > 2 && n % 2 === 0) {
574
+ return false;
575
+ }
576
+ for (let i = 3, sqrt = Math.sqrt(n); i <= sqrt; i += 2) {
577
+ if (n % i === 0) {
578
+ return false;
579
+ }
580
+ }
581
+ return true;
582
+ },
583
+ // @ts-expect-error - TS2366 - Function lacks ending return statement and return type does not include 'undefined'.
584
+ getPrimeFactorization: function (number) {
585
+ if (number === 1) {
586
+ return [];
587
+ }
588
+ if (KhanMath.isPrime(number)) {
589
+ return [number];
590
+ }
591
+ const maxf = Math.sqrt(number);
592
+ for (let f = 2; f <= maxf; f++) {
593
+ if (number % f === 0) {
594
+ return $.merge(KhanMath.getPrimeFactorization(f), KhanMath.getPrimeFactorization(number / f));
595
+ }
596
+ }
597
+ },
598
+ // Round a number to the nearest increment
599
+ // E.g., if increment = 30 and num = 40, return 30. if increment = 30 and
600
+ // num = 45, return 60.
601
+ roundToNearest: function (increment, num) {
602
+ return Math.round(num / increment) * increment;
603
+ },
604
+ // Round a number to a certain number of decimal places
605
+ roundTo: function (precision, num) {
606
+ const factor = Math.pow(10, precision).toFixed(5);
607
+ // @ts-expect-error - TS2345 - Argument of type 'string' is not assignable to parameter of type 'number'. | TS2363 - The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. | TS2363 - The right-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.
608
+ return Math.round((num * factor).toFixed(5)) / factor;
609
+ },
610
+ /**
611
+ * Return a string of num rounded to a fixed precision decimal places,
612
+ * with an approx symbol if num had to be rounded, and trailing 0s
613
+ */
614
+ toFixedApprox: function (num, precision) {
615
+ // TODO(aria): Make this locale-dependent
616
+ const fixedStr = num.toFixed(precision);
617
+ if (equal$4(+fixedStr, num)) {
618
+ return fixedStr;
619
+ }
620
+ return "\\approx " + fixedStr;
621
+ },
622
+ /**
623
+ * Return a string of num rounded to precision decimal places, with an
624
+ * approx symbol if num had to be rounded, but no trailing 0s if it was
625
+ * not rounded.
626
+ */
627
+ roundToApprox: function (num, precision) {
628
+ const fixed = KhanMath.roundTo(precision, num);
629
+ if (equal$4(fixed, num)) {
630
+ return String(fixed);
631
+ }
632
+ return KhanMath.toFixedApprox(num, precision);
633
+ },
634
+ // toFraction(4/8) => [1, 2]
635
+ // toFraction(0.666) => [333, 500]
636
+ // toFraction(0.666, 0.001) => [2, 3]
637
+ //
638
+ // tolerance can't be bigger than 1, sorry
639
+ toFraction: function (decimal, tolerance) {
640
+ if (tolerance == null) {
641
+ tolerance = Math.pow(2, -46);
642
+ }
643
+ if (decimal < 0 || decimal > 1) {
644
+ let fract = decimal % 1;
645
+ fract += fract < 0 ? 1 : 0;
646
+ const nd = KhanMath.toFraction(fract, tolerance);
647
+ nd[0] += Math.round(decimal - fract) * nd[1];
648
+ return nd;
649
+ }
650
+ if (Math.abs(Math.round(Number(decimal)) - decimal) <= tolerance) {
651
+ return [Math.round(decimal), 1];
652
+ }
653
+ let loN = 0;
654
+ let loD = 1;
655
+ let hiN = 1;
656
+ let hiD = 1;
657
+ let midN = 1;
658
+ let midD = 2;
659
+
660
+ // eslint-disable-next-line no-constant-condition
661
+ while (true) {
662
+ if (Math.abs(Number(midN / midD) - decimal) <= tolerance) {
663
+ return [midN, midD];
664
+ }
665
+ if (midN / midD < decimal) {
666
+ loN = midN;
667
+ loD = midD;
668
+ } else {
669
+ hiN = midN;
670
+ hiD = midD;
671
+ }
672
+ midN = loN + hiN;
673
+ midD = loD + hiD;
674
+ }
675
+ },
676
+ // Returns the format (string) of a given numeric string
677
+ // Note: purposively more inclusive than answer-types' predicate.forms
678
+ // That is, it is not necessarily true that interpreted input are numeric
679
+ getNumericFormat: function (text) {
680
+ text = $.trim(text);
681
+ text = text.replace(/\u2212/, "-").replace(/([+-])\s+/g, "$1");
682
+ if (text.match(/^[+-]?\d+$/)) {
683
+ return "integer";
684
+ }
685
+ if (text.match(/^[+-]?\d+\s+\d+\s*\/\s*\d+$/)) {
686
+ return "mixed";
687
+ }
688
+ const fraction = text.match(/^[+-]?(\d+)\s*\/\s*(\d+)$/);
689
+ if (fraction) {
690
+ return parseFloat(fraction[1]) > parseFloat(fraction[2]) ? "improper" : "proper";
691
+ }
692
+ if (text.replace(/[,. ]/g, "").match(/^\d+$/)) {
693
+ return "decimal";
694
+ }
695
+ if (text.match(/(pi?|\u03c0|t(?:au)?|\u03c4|pau)/)) {
696
+ return "pi";
697
+ }
698
+ return null;
699
+ },
700
+ // Returns a string of the number in a specified format
701
+ toNumericString: function (number$1, format) {
702
+ if (number$1 == null) {
703
+ return "";
704
+ }
705
+ if (number$1 === 0) {
706
+ return "0"; // otherwise it might end up as 0% or 0pi
707
+ }
708
+ if (format === "percent") {
709
+ return number$1 * 100 + "%";
710
+ }
711
+ if (format === "pi") {
712
+ const fraction = toFraction(number$1 / Math.PI);
713
+ const numerator = Math.abs(fraction[0]);
714
+ const denominator = fraction[1];
715
+ if (isInteger(numerator)) {
716
+ const sign = number$1 < 0 ? "-" : "";
717
+ const pi = "\u03C0";
718
+ return sign + (numerator === 1 ? "" : numerator) + pi + (denominator === 1 ? "" : "/" + denominator);
719
+ }
720
+ }
721
+ if (_(["proper", "improper", "mixed", "fraction"]).contains(format)) {
722
+ const fraction = toFraction(number$1);
723
+ const numerator = Math.abs(fraction[0]);
724
+ const denominator = fraction[1];
725
+ const sign = number$1 < 0 ? "-" : "";
726
+ if (denominator === 1) {
727
+ return sign + numerator; // for integers, irrational, d > 1000
728
+ }
729
+ if (format === "mixed") {
730
+ const modulus = numerator % denominator;
731
+ const integer = (numerator - modulus) / denominator;
732
+ return sign + (
733
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
734
+ integer ? integer + " " : "") + modulus + "/" + denominator;
735
+ } // otherwise proper, improper, or fraction
736
+ return sign + numerator + "/" + denominator;
737
+ }
738
+
739
+ // otherwise (decimal, float, long long)
740
+ return String(number$1);
741
+ }
742
+ };
743
+ function sum(array) {
744
+ return array.reduce(add, 0);
745
+ }
746
+ function add(a, b) {
747
+ return a + b;
748
+ }
749
+
750
+ /**
751
+ * A collection of geomtry-related utility functions
752
+ */
753
+
754
+
755
+ // This should really be a readonly tuple of [number, number]
756
+
757
+ // Given a number, return whether it is positive (1), negative (-1), or zero (0)
758
+ function sign(val) {
759
+ if (approximateEqual(val, 0)) {
760
+ return 0;
761
+ }
762
+ return val > 0 ? 1 : -1;
763
+ }
764
+
765
+ // Determine whether three points are collinear (0), for a clockwise turn (negative),
766
+ // or counterclockwise turn (positive)
767
+ function ccw(a, b, c) {
768
+ return (b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1]);
769
+ }
770
+ function collinear(a, b, c) {
771
+ return approximateEqual(ccw(a, b, c), 0);
772
+ }
773
+
774
+ // Given rect bounding points A and B, whether point C is inside the rect
775
+ function pointInRect(a, b, c) {
776
+ return c[0] <= Math.max(a[0], b[0]) && c[0] >= Math.min(a[0], b[0]) && c[1] <= Math.max(a[1], b[1]) && c[1] >= Math.min(a[1], b[1]);
777
+ }
778
+
779
+ // Whether line segment AB intersects line segment CD
780
+ // http://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
781
+ function intersects(ab, cd) {
782
+ const triplets = [[ab[0], ab[1], cd[0]], [ab[0], ab[1], cd[1]], [cd[0], cd[1], ab[0]], [cd[0], cd[1], ab[1]]];
783
+ const orientations = _.map(triplets, function (triplet) {
784
+ return sign(ccw(...triplet));
785
+ });
786
+ if (orientations[0] !== orientations[1] && orientations[2] !== orientations[3]) {
787
+ return true;
788
+ }
789
+ for (let i = 0; i < 4; i++) {
790
+ if (orientations[i] === 0 && pointInRect(...triplets[i])) {
791
+ return true;
792
+ }
793
+ }
794
+ return false;
795
+ }
796
+
797
+ // Whether any two sides of a polygon intersect each other
798
+ function polygonSidesIntersect(vertices) {
799
+ for (let i = 0; i < vertices.length; i++) {
800
+ for (let k = i + 1; k < vertices.length; k++) {
801
+ // If any two vertices are the same point, sides overlap
802
+ if (equal$2(vertices[i], vertices[k])) {
803
+ return true;
804
+ }
805
+
806
+ // Find the other end of the sides starting at vertices i and k
807
+ const iNext = (i + 1) % vertices.length;
808
+ const kNext = (k + 1) % vertices.length;
809
+
810
+ // Adjacent sides always intersect (at the vertex); skip those
811
+ if (iNext === k || kNext === i) {
812
+ continue;
813
+ }
814
+ const side1 = [vertices[i], vertices[iNext]];
815
+ const side2 = [vertices[k], vertices[kNext]];
816
+ if (intersects(side1, side2)) {
817
+ return true;
818
+ }
819
+ }
820
+ }
821
+ return false;
822
+ }
823
+ function vector(a, b) {
824
+ return _.map(_.zip(a, b), function (pair) {
825
+ return pair[0] - pair[1];
826
+ });
827
+ }
828
+ function reverseVector(vector) {
829
+ return [-vector[0], -vector[1]];
830
+ }
831
+
832
+ // Returns whether connecting the given sequence of `points` forms a clockwise
833
+ // path (assuming a closed loop, where the last point connects back to the
834
+ // first).
835
+ function clockwise(points) {
836
+ const segments = _.zip(points, points.slice(1).concat(points.slice(0, 1)));
837
+ const areas = _.map(segments, function (segment) {
838
+ const p1 = segment[0];
839
+ const p2 = segment[1];
840
+ return (p2[0] - p1[0]) * (p2[1] + p1[1]);
841
+ });
842
+ return sum(areas) > 0;
843
+ }
844
+ function magnitude(v) {
845
+ return Math.sqrt(_.reduce(v, function (memo, el) {
846
+ // @ts-expect-error - TS2345 - Argument of type 'Coord' is not assignable to parameter of type 'number'.
847
+ return memo + Math.pow(el, 2);
848
+ }, 0));
849
+ }
850
+ function dotProduct(a, b) {
851
+ return _.reduce(_.zip(a, b), function (memo, pair) {
852
+ return memo + pair[0] * pair[1];
853
+ }, 0);
854
+ }
855
+ function sideLengths(coords) {
856
+ const segments = _.zip(coords, rotate(coords));
857
+ return segments.map(function (segment) {
858
+ // @ts-expect-error - TS2345 - Argument of type 'number[]' is not assignable to parameter of type 'readonly Coord[]'. | TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
859
+ return magnitude(vector(...segment));
860
+ });
861
+ }
862
+
863
+ // Based on http://math.stackexchange.com/a/151149
864
+ function angleMeasures(coords) {
865
+ const triplets = _.zip(rotate(coords, -1), coords, rotate(coords, 1));
866
+ const offsets = _.map(triplets, function (triplet) {
867
+ const p = vector(triplet[1], triplet[0]);
868
+ const q = vector(triplet[2], triplet[1]);
869
+ // @ts-expect-error - TS2345 - Argument of type 'number[]' is not assignable to parameter of type 'Coord'. | TS2345 - Argument of type 'number[]' is not assignable to parameter of type 'readonly Coord[]'. | TS2345 - Argument of type 'number[]' is not assignable to parameter of type 'readonly Coord[]'.
870
+ const raw = Math.acos(dotProduct(p, q) / (magnitude(p) * magnitude(q)));
871
+ // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
872
+ return sign(ccw(...triplet)) > 0 ? raw : -raw;
873
+ });
874
+ const sum = _.reduce(offsets, function (memo, arg) {
875
+ return memo + arg;
876
+ }, 0);
877
+ return _.map(offsets, function (offset) {
878
+ return sum > 0 ? Math.PI - offset : Math.PI + offset;
879
+ });
880
+ }
881
+
882
+ // Whether two polygons are similar (or if specified, congruent)
883
+ function similar(coords1, coords2, tolerance) {
884
+ if (coords1.length !== coords2.length) {
885
+ return false;
886
+ }
887
+ const n = coords1.length;
888
+ const angles1 = angleMeasures(coords1);
889
+ const angles2 = angleMeasures(coords2);
890
+ const sides1 = sideLengths(coords1);
891
+ const sides2 = sideLengths(coords2);
892
+ for (let i = 0; i < 2 * n; i++) {
893
+ let angles = angles2.slice();
894
+ let sides = sides2.slice();
895
+
896
+ // Reverse angles and sides to allow matching reflected polygons
897
+ if (i >= n) {
898
+ angles.reverse();
899
+ sides.reverse();
900
+ // Since sides are calculated from two coordinates,
901
+ // simply reversing results in an off by one error
902
+ // @ts-expect-error - TS4104 - The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
903
+ sides = rotate(sides, 1);
904
+ }
905
+
906
+ // @ts-expect-error - TS4104 - The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
907
+ angles = rotate(angles, i);
908
+ // @ts-expect-error - TS4104 - The type 'readonly number[]' is 'readonly' and cannot be assigned to the mutable type 'number[]'.
909
+ sides = rotate(sides, i);
910
+ if (approximateDeepEqual(angles1, angles)) {
911
+ const sidePairs = _.zip(sides1, sides);
912
+ const factors = _.map(sidePairs, function (pair) {
913
+ return pair[0] / pair[1];
914
+ });
915
+ const same = _.all(factors, function (factor) {
916
+ return approximateEqual(factors[0], factor);
917
+ });
918
+ const congruentEnough = _.all(sidePairs, function (pair) {
919
+ return equal$4(pair[0], pair[1], tolerance);
920
+ });
921
+ if (same && congruentEnough) {
922
+ return true;
923
+ }
924
+ }
925
+ }
926
+ return false;
927
+ }
928
+
929
+ // Given triangle with sides ABC return angle opposite side C in degrees
930
+ function lawOfCosines(a, b, c) {
931
+ return Math.acos((a * a + b * b - c * c) / (2 * a * b)) * 180 / Math.PI;
932
+ }
933
+ function canonicalSineCoefficients([amplitude, angularFrequency, phase, verticalOffset]) {
934
+ // For a curve of the form f(x) = a * Sin(b * x - c) + d,
935
+ // this function ensures that a, b > 0, and c is its
936
+ // smallest possible positive value.
937
+
938
+ // Guarantee a > 0
939
+ if (amplitude < 0) {
940
+ amplitude *= -1;
941
+ angularFrequency *= -1;
942
+ phase *= -1;
943
+ }
944
+ const period = 2 * Math.PI;
945
+ // Guarantee b > 0
946
+ if (angularFrequency < 0) {
947
+ angularFrequency *= -1;
948
+ phase *= -1;
949
+ phase += period / 2;
950
+ }
951
+
952
+ // Guarantee c is smallest possible positive value
953
+ while (phase > 0) {
954
+ phase -= period;
955
+ }
956
+ while (phase < 0) {
957
+ phase += period;
958
+ }
959
+ return [amplitude, angularFrequency, phase, verticalOffset];
960
+ }
961
+
962
+ // e.g. rotate([1, 2, 3]) -> [2, 3, 1]
963
+ function rotate(array, n) {
964
+ n = typeof n === "undefined" ? 1 : n % array.length;
965
+ return array.slice(n).concat(array.slice(0, n));
966
+ }
967
+ function getLineEquation(first, second) {
968
+ if (approximateEqual(first[0], second[0])) {
969
+ return "x = " + first[0].toFixed(3);
970
+ }
971
+ const m = (second[1] - first[1]) / (second[0] - first[0]);
972
+ const b = first[1] - m * first[0];
973
+ return "y = " + m.toFixed(3) + "x + " + b.toFixed(3);
974
+ }
975
+
976
+ // Stolen from the wikipedia article
977
+ // http://en.wikipedia.org/wiki/Line-line_intersection
978
+ function getLineIntersection(
979
+ // TODO(LP-10725): update these to be 2-tuples
980
+ firstPoints, secondPoints) {
981
+ const x1 = firstPoints[0][0];
982
+ const y1 = firstPoints[0][1];
983
+ const x2 = firstPoints[1][0];
984
+ const y2 = firstPoints[1][1];
985
+ const x3 = secondPoints[0][0];
986
+ const y3 = secondPoints[0][1];
987
+ const x4 = secondPoints[1][0];
988
+ const y4 = secondPoints[1][1];
989
+ const determinant = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4);
990
+ if (Math.abs(determinant) < 1e-9) {
991
+ // Lines are parallel
992
+ return null;
993
+ }
994
+ const x = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / determinant;
995
+ const y = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / determinant;
996
+ return [x, y];
997
+ }
998
+ function getLineIntersectionString(firstPoints, secondPoints) {
999
+ const intersection = getLineIntersection(firstPoints, secondPoints);
1000
+ if (intersection === null) {
1001
+ return "Lines are parallel";
1002
+ }
1003
+ const [x, y] = intersection;
1004
+ return "Intersection: (" + x.toFixed(3) + ", " + y.toFixed(3) + ")";
1005
+ }
1006
+
1007
+ var geometry = /*#__PURE__*/Object.freeze({
1008
+ __proto__: null,
1009
+ angleMeasures: angleMeasures,
1010
+ canonicalSineCoefficients: canonicalSineCoefficients,
1011
+ ccw: ccw,
1012
+ clockwise: clockwise,
1013
+ collinear: collinear,
1014
+ getLineEquation: getLineEquation,
1015
+ getLineIntersection: getLineIntersection,
1016
+ getLineIntersectionString: getLineIntersectionString,
1017
+ intersects: intersects,
1018
+ lawOfCosines: lawOfCosines,
1019
+ magnitude: magnitude,
1020
+ polygonSidesIntersect: polygonSidesIntersect,
1021
+ reverseVector: reverseVector,
1022
+ rotate: rotate,
1023
+ sign: sign,
1024
+ similar: similar,
1025
+ vector: vector
1026
+ });
1027
+
1028
+ // This file contains helper functions for working with angles.
1029
+
1030
+ function convertDegreesToRadians(degrees) {
1031
+ return degrees / 180 * Math.PI;
1032
+ }
1033
+ function convertRadiansToDegrees(radians) {
1034
+ const degree = radians / Math.PI * 180;
1035
+ // Account for floating point errors.
1036
+ return Number(degree.toPrecision(15));
1037
+ }
1038
+
1039
+ // Returns a value between -180 and 180, inclusive. The angle is measured
1040
+ // between the positive x-axis and the given vector.
1041
+ function calculateAngleInDegrees([x, y]) {
1042
+ return Math.atan2(y, x) * 180 / Math.PI;
1043
+ }
1044
+
1045
+ // Converts polar coordinates to cartesian. The th(eta) parameter is in degrees.
1046
+ function polar(r, th) {
1047
+ if (typeof r === "number") {
1048
+ r = [r, r];
1049
+ }
1050
+ th = th * Math.PI / 180;
1051
+ return [r[0] * Math.cos(th), r[1] * Math.sin(th)];
1052
+ }
1053
+ // This function calculates the angle between two points and an optional vertex.
1054
+ // If the vertex is not provided, the angle is measured between the two points.
1055
+ // This does not account for reflex angles or clockwise position.
1056
+ const getAngleFromVertex = (point, vertex) => {
1057
+ const x = point[0] - vertex[0];
1058
+ const y = point[1] - vertex[1];
1059
+ // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions
1060
+ if (!x && !y) {
1061
+ return 0;
1062
+ }
1063
+ return (180 + Math.atan2(-y, -x) * 180 / Math.PI + 360) % 360;
1064
+ };
1065
+
1066
+ // This function calculates the clockwise angle between three points,
1067
+ // and is used to generate the labels and equation strings of the
1068
+ // current angle for the interactive graph.
1069
+ const getClockwiseAngle = (coords, allowReflexAngles = false) => {
1070
+ const coordsCopy = [...coords];
1071
+ // The coords are saved as [point1, vertex, point2] in the interactive graph
1072
+ const areClockwise = clockwise([coordsCopy[0], coordsCopy[2], coordsCopy[1]]);
1073
+
1074
+ // We may need to reverse the coordinates if we allow
1075
+ // reflex angles and the points are not in clockwise order.
1076
+ const shouldReverseCoords = !areClockwise || allowReflexAngles;
1077
+
1078
+ // Reverse the coordinates accordingly to ensure the angle is calculated correctly
1079
+ const clockwiseCoords = shouldReverseCoords ? coordsCopy.reverse() : coordsCopy;
1080
+
1081
+ // Calculate the angles between the two points and get the difference
1082
+ // between the two angles to get the clockwise angle.
1083
+ const startAngle = getAngleFromVertex(clockwiseCoords[0], clockwiseCoords[1]);
1084
+ const endAngle = getAngleFromVertex(clockwiseCoords[2], clockwiseCoords[1]);
1085
+ const angle = (startAngle + 360 - endAngle) % 360;
1086
+ return angle;
1087
+ };
1088
+
1089
+ var angles = /*#__PURE__*/Object.freeze({
1090
+ __proto__: null,
1091
+ calculateAngleInDegrees: calculateAngleInDegrees,
1092
+ convertDegreesToRadians: convertDegreesToRadians,
1093
+ convertRadiansToDegrees: convertRadiansToDegrees,
1094
+ getAngleFromVertex: getAngleFromVertex,
1095
+ getClockwiseAngle: getClockwiseAngle,
1096
+ polar: polar
1097
+ });
1098
+
1099
+ // TODO: there's another, very similar getSinusoidCoefficients function
1100
+ // they should probably be merged
1101
+ function getSinusoidCoefficients(coords) {
1102
+ // It's assumed that p1 is the root and p2 is the first peak
1103
+ const p1 = coords[0];
1104
+ const p2 = coords[1];
1105
+
1106
+ // Resulting coefficients are canonical for this sine curve
1107
+ const amplitude = p2[1] - p1[1];
1108
+ const angularFrequency = Math.PI / (2 * (p2[0] - p1[0]));
1109
+ const phase = p1[0] * angularFrequency;
1110
+ const verticalOffset = p1[1];
1111
+ return [amplitude, angularFrequency, phase, verticalOffset];
1112
+ }
1113
+ // TODO: there's another, very similar getQuadraticCoefficients function
1114
+ // they should probably be merged
1115
+ function getQuadraticCoefficients(coords) {
1116
+ const p1 = coords[0];
1117
+ const p2 = coords[1];
1118
+ const p3 = coords[2];
1119
+ const denom = (p1[0] - p2[0]) * (p1[0] - p3[0]) * (p2[0] - p3[0]);
1120
+ if (denom === 0) {
1121
+ // Many of the callers assume that the return value is always defined.
1122
+ // @ts-expect-error - TS2322 - Type 'undefined' is not assignable to type 'QuadraticCoefficient'.
1123
+ return;
1124
+ }
1125
+ const a = (p3[0] * (p2[1] - p1[1]) + p2[0] * (p1[1] - p3[1]) + p1[0] * (p3[1] - p2[1])) / denom;
1126
+ const b = (p3[0] * p3[0] * (p1[1] - p2[1]) + p2[0] * p2[0] * (p3[1] - p1[1]) + p1[0] * p1[0] * (p2[1] - p3[1])) / denom;
1127
+ const c = (p2[0] * p3[0] * (p2[0] - p3[0]) * p1[1] + p3[0] * p1[0] * (p3[0] - p1[0]) * p2[1] + p1[0] * p2[0] * (p1[0] - p2[0]) * p3[1]) / denom;
1128
+ return [a, b, c];
1129
+ }
1130
+
1131
+ var coefficients = /*#__PURE__*/Object.freeze({
1132
+ __proto__: null,
1133
+ getQuadraticCoefficients: getQuadraticCoefficients,
1134
+ getSinusoidCoefficients: getSinusoidCoefficients
1135
+ });
1136
+
1137
+ export { KhanMath, angles, coefficients, geometry, libVersion, line, number, point, ray, sum, vector$1 as vector };
1138
+ //# sourceMappingURL=index.js.map