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