@khanacademy/perseus-core 3.0.5 → 3.2.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 CHANGED
@@ -40,9 +40,2547 @@ const addLibraryVersionToPerseusDebug = (libraryName, libraryVersion) => {
40
40
  }
41
41
  };
42
42
 
43
+ // Current version.
44
+ var VERSION = '1.13.3';
45
+
46
+ // Establish the root object, `window` (`self`) in the browser, `global`
47
+ // on the server, or `this` in some virtual machines. We use `self`
48
+ // instead of `window` for `WebWorker` support.
49
+ var root = (typeof self == 'object' && self.self === self && self) ||
50
+ (typeof global == 'object' && global.global === global && global) ||
51
+ Function('return this')() ||
52
+ {};
53
+
54
+ // Save bytes in the minified (but not gzipped) version:
55
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype;
56
+ var SymbolProto = typeof Symbol !== 'undefined' ? Symbol.prototype : null;
57
+
58
+ // Create quick reference variables for speed access to core prototypes.
59
+ var push = ArrayProto.push,
60
+ slice = ArrayProto.slice,
61
+ toString = ObjProto.toString,
62
+ hasOwnProperty = ObjProto.hasOwnProperty;
63
+
64
+ // Modern feature detection.
65
+ var supportsArrayBuffer = typeof ArrayBuffer !== 'undefined',
66
+ supportsDataView = typeof DataView !== 'undefined';
67
+
68
+ // All **ECMAScript 5+** native function implementations that we hope to use
69
+ // are declared here.
70
+ var nativeIsArray = Array.isArray,
71
+ nativeKeys = Object.keys,
72
+ nativeCreate = Object.create,
73
+ nativeIsView = supportsArrayBuffer && ArrayBuffer.isView;
74
+
75
+ // Create references to these builtin functions because we override them.
76
+ var _isNaN = isNaN,
77
+ _isFinite = isFinite;
78
+
79
+ // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed.
80
+ var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString');
81
+ var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
82
+ 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
83
+
84
+ // The largest integer that can be represented exactly.
85
+ var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1;
86
+
87
+ // Some functions take a variable number of arguments, or a few expected
88
+ // arguments at the beginning and then a variable number of values to operate
89
+ // on. This helper accumulates all remaining arguments past the function’s
90
+ // argument length (or an explicit `startIndex`), into an array that becomes
91
+ // the last argument. Similar to ES6’s "rest parameter".
92
+ function restArguments(func, startIndex) {
93
+ startIndex = startIndex == null ? func.length - 1 : +startIndex;
94
+ return function() {
95
+ var length = Math.max(arguments.length - startIndex, 0),
96
+ rest = Array(length),
97
+ index = 0;
98
+ for (; index < length; index++) {
99
+ rest[index] = arguments[index + startIndex];
100
+ }
101
+ switch (startIndex) {
102
+ case 0: return func.call(this, rest);
103
+ case 1: return func.call(this, arguments[0], rest);
104
+ case 2: return func.call(this, arguments[0], arguments[1], rest);
105
+ }
106
+ var args = Array(startIndex + 1);
107
+ for (index = 0; index < startIndex; index++) {
108
+ args[index] = arguments[index];
109
+ }
110
+ args[startIndex] = rest;
111
+ return func.apply(this, args);
112
+ };
113
+ }
114
+
115
+ // Is a given variable an object?
116
+ function isObject(obj) {
117
+ var type = typeof obj;
118
+ return type === 'function' || (type === 'object' && !!obj);
119
+ }
120
+
121
+ // Is a given value equal to null?
122
+ function isNull(obj) {
123
+ return obj === null;
124
+ }
125
+
126
+ // Is a given variable undefined?
127
+ function isUndefined(obj) {
128
+ return obj === void 0;
129
+ }
130
+
131
+ // Is a given value a boolean?
132
+ function isBoolean(obj) {
133
+ return obj === true || obj === false || toString.call(obj) === '[object Boolean]';
134
+ }
135
+
136
+ // Is a given value a DOM element?
137
+ function isElement(obj) {
138
+ return !!(obj && obj.nodeType === 1);
139
+ }
140
+
141
+ // Internal function for creating a `toString`-based type tester.
142
+ function tagTester(name) {
143
+ var tag = '[object ' + name + ']';
144
+ return function(obj) {
145
+ return toString.call(obj) === tag;
146
+ };
147
+ }
148
+
149
+ var isString = tagTester('String');
150
+
151
+ var isNumber = tagTester('Number');
152
+
153
+ var isDate = tagTester('Date');
154
+
155
+ var isRegExp = tagTester('RegExp');
156
+
157
+ var isError = tagTester('Error');
158
+
159
+ var isSymbol = tagTester('Symbol');
160
+
161
+ var isArrayBuffer = tagTester('ArrayBuffer');
162
+
163
+ var isFunction = tagTester('Function');
164
+
165
+ // Optimize `isFunction` if appropriate. Work around some `typeof` bugs in old
166
+ // v8, IE 11 (#1621), Safari 8 (#1929), and PhantomJS (#2236).
167
+ var nodelist = root.document && root.document.childNodes;
168
+ if (typeof /./ != 'function' && typeof Int8Array != 'object' && typeof nodelist != 'function') {
169
+ isFunction = function(obj) {
170
+ return typeof obj == 'function' || false;
171
+ };
172
+ }
173
+
174
+ var isFunction$1 = isFunction;
175
+
176
+ var hasObjectTag = tagTester('Object');
177
+
178
+ // In IE 10 - Edge 13, `DataView` has string tag `'[object Object]'`.
179
+ // In IE 11, the most common among them, this problem also applies to
180
+ // `Map`, `WeakMap` and `Set`.
181
+ var hasStringTagBug = (
182
+ supportsDataView && hasObjectTag(new DataView(new ArrayBuffer(8)))
183
+ ),
184
+ isIE11 = (typeof Map !== 'undefined' && hasObjectTag(new Map));
185
+
186
+ var isDataView = tagTester('DataView');
187
+
188
+ // In IE 10 - Edge 13, we need a different heuristic
189
+ // to determine whether an object is a `DataView`.
190
+ function ie10IsDataView(obj) {
191
+ return obj != null && isFunction$1(obj.getInt8) && isArrayBuffer(obj.buffer);
192
+ }
193
+
194
+ var isDataView$1 = (hasStringTagBug ? ie10IsDataView : isDataView);
195
+
196
+ // Is a given value an array?
197
+ // Delegates to ECMA5's native `Array.isArray`.
198
+ var isArray = nativeIsArray || tagTester('Array');
199
+
200
+ // Internal function to check whether `key` is an own property name of `obj`.
201
+ function has$1(obj, key) {
202
+ return obj != null && hasOwnProperty.call(obj, key);
203
+ }
204
+
205
+ var isArguments = tagTester('Arguments');
206
+
207
+ // Define a fallback version of the method in browsers (ahem, IE < 9), where
208
+ // there isn't any inspectable "Arguments" type.
209
+ (function() {
210
+ if (!isArguments(arguments)) {
211
+ isArguments = function(obj) {
212
+ return has$1(obj, 'callee');
213
+ };
214
+ }
215
+ }());
216
+
217
+ var isArguments$1 = isArguments;
218
+
219
+ // Is a given object a finite number?
220
+ function isFinite$1(obj) {
221
+ return !isSymbol(obj) && _isFinite(obj) && !isNaN(parseFloat(obj));
222
+ }
223
+
224
+ // Is the given value `NaN`?
225
+ function isNaN$1(obj) {
226
+ return isNumber(obj) && _isNaN(obj);
227
+ }
228
+
229
+ // Predicate-generating function. Often useful outside of Underscore.
230
+ function constant(value) {
231
+ return function() {
232
+ return value;
233
+ };
234
+ }
235
+
236
+ // Common internal logic for `isArrayLike` and `isBufferLike`.
237
+ function createSizePropertyCheck(getSizeProperty) {
238
+ return function(collection) {
239
+ var sizeProperty = getSizeProperty(collection);
240
+ return typeof sizeProperty == 'number' && sizeProperty >= 0 && sizeProperty <= MAX_ARRAY_INDEX;
241
+ }
242
+ }
243
+
244
+ // Internal helper to generate a function to obtain property `key` from `obj`.
245
+ function shallowProperty(key) {
246
+ return function(obj) {
247
+ return obj == null ? void 0 : obj[key];
248
+ };
249
+ }
250
+
251
+ // Internal helper to obtain the `byteLength` property of an object.
252
+ var getByteLength = shallowProperty('byteLength');
253
+
254
+ // Internal helper to determine whether we should spend extensive checks against
255
+ // `ArrayBuffer` et al.
256
+ var isBufferLike = createSizePropertyCheck(getByteLength);
257
+
258
+ // Is a given value a typed array?
259
+ var typedArrayPattern = /\[object ((I|Ui)nt(8|16|32)|Float(32|64)|Uint8Clamped|Big(I|Ui)nt64)Array\]/;
260
+ function isTypedArray(obj) {
261
+ // `ArrayBuffer.isView` is the most future-proof, so use it when available.
262
+ // Otherwise, fall back on the above regular expression.
263
+ return nativeIsView ? (nativeIsView(obj) && !isDataView$1(obj)) :
264
+ isBufferLike(obj) && typedArrayPattern.test(toString.call(obj));
265
+ }
266
+
267
+ var isTypedArray$1 = supportsArrayBuffer ? isTypedArray : constant(false);
268
+
269
+ // Internal helper to obtain the `length` property of an object.
270
+ var getLength = shallowProperty('length');
271
+
272
+ // Internal helper to create a simple lookup structure.
273
+ // `collectNonEnumProps` used to depend on `_.contains`, but this led to
274
+ // circular imports. `emulatedSet` is a one-off solution that only works for
275
+ // arrays of strings.
276
+ function emulatedSet(keys) {
277
+ var hash = {};
278
+ for (var l = keys.length, i = 0; i < l; ++i) hash[keys[i]] = true;
279
+ return {
280
+ contains: function(key) { return hash[key] === true; },
281
+ push: function(key) {
282
+ hash[key] = true;
283
+ return keys.push(key);
284
+ }
285
+ };
286
+ }
287
+
288
+ // Internal helper. Checks `keys` for the presence of keys in IE < 9 that won't
289
+ // be iterated by `for key in ...` and thus missed. Extends `keys` in place if
290
+ // needed.
291
+ function collectNonEnumProps(obj, keys) {
292
+ keys = emulatedSet(keys);
293
+ var nonEnumIdx = nonEnumerableProps.length;
294
+ var constructor = obj.constructor;
295
+ var proto = (isFunction$1(constructor) && constructor.prototype) || ObjProto;
296
+
297
+ // Constructor is a special case.
298
+ var prop = 'constructor';
299
+ if (has$1(obj, prop) && !keys.contains(prop)) keys.push(prop);
300
+
301
+ while (nonEnumIdx--) {
302
+ prop = nonEnumerableProps[nonEnumIdx];
303
+ if (prop in obj && obj[prop] !== proto[prop] && !keys.contains(prop)) {
304
+ keys.push(prop);
305
+ }
306
+ }
307
+ }
308
+
309
+ // Retrieve the names of an object's own properties.
310
+ // Delegates to **ECMAScript 5**'s native `Object.keys`.
311
+ function keys(obj) {
312
+ if (!isObject(obj)) return [];
313
+ if (nativeKeys) return nativeKeys(obj);
314
+ var keys = [];
315
+ for (var key in obj) if (has$1(obj, key)) keys.push(key);
316
+ // Ahem, IE < 9.
317
+ if (hasEnumBug) collectNonEnumProps(obj, keys);
318
+ return keys;
319
+ }
320
+
321
+ // Is a given array, string, or object empty?
322
+ // An "empty" object has no enumerable own-properties.
323
+ function isEmpty(obj) {
324
+ if (obj == null) return true;
325
+ // Skip the more expensive `toString`-based type checks if `obj` has no
326
+ // `.length`.
327
+ var length = getLength(obj);
328
+ if (typeof length == 'number' && (
329
+ isArray(obj) || isString(obj) || isArguments$1(obj)
330
+ )) return length === 0;
331
+ return getLength(keys(obj)) === 0;
332
+ }
333
+
334
+ // Returns whether an object has a given set of `key:value` pairs.
335
+ function isMatch(object, attrs) {
336
+ var _keys = keys(attrs), length = _keys.length;
337
+ if (object == null) return !length;
338
+ var obj = Object(object);
339
+ for (var i = 0; i < length; i++) {
340
+ var key = _keys[i];
341
+ if (attrs[key] !== obj[key] || !(key in obj)) return false;
342
+ }
343
+ return true;
344
+ }
345
+
346
+ // If Underscore is called as a function, it returns a wrapped object that can
347
+ // be used OO-style. This wrapper holds altered versions of all functions added
348
+ // through `_.mixin`. Wrapped objects may be chained.
349
+ function _$1(obj) {
350
+ if (obj instanceof _$1) return obj;
351
+ if (!(this instanceof _$1)) return new _$1(obj);
352
+ this._wrapped = obj;
353
+ }
354
+
355
+ _$1.VERSION = VERSION;
356
+
357
+ // Extracts the result from a wrapped and chained object.
358
+ _$1.prototype.value = function() {
359
+ return this._wrapped;
360
+ };
361
+
362
+ // Provide unwrapping proxies for some methods used in engine operations
363
+ // such as arithmetic and JSON stringification.
364
+ _$1.prototype.valueOf = _$1.prototype.toJSON = _$1.prototype.value;
365
+
366
+ _$1.prototype.toString = function() {
367
+ return String(this._wrapped);
368
+ };
369
+
370
+ // Internal function to wrap or shallow-copy an ArrayBuffer,
371
+ // typed array or DataView to a new view, reusing the buffer.
372
+ function toBufferView(bufferSource) {
373
+ return new Uint8Array(
374
+ bufferSource.buffer || bufferSource,
375
+ bufferSource.byteOffset || 0,
376
+ getByteLength(bufferSource)
377
+ );
378
+ }
379
+
380
+ // We use this string twice, so give it a name for minification.
381
+ var tagDataView = '[object DataView]';
382
+
383
+ // Internal recursive comparison function for `_.isEqual`.
384
+ function eq(a, b, aStack, bStack) {
385
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
386
+ // See the [Harmony `egal` proposal](https://wiki.ecmascript.org/doku.php?id=harmony:egal).
387
+ if (a === b) return a !== 0 || 1 / a === 1 / b;
388
+ // `null` or `undefined` only equal to itself (strict comparison).
389
+ if (a == null || b == null) return false;
390
+ // `NaN`s are equivalent, but non-reflexive.
391
+ if (a !== a) return b !== b;
392
+ // Exhaust primitive checks
393
+ var type = typeof a;
394
+ if (type !== 'function' && type !== 'object' && typeof b != 'object') return false;
395
+ return deepEq(a, b, aStack, bStack);
396
+ }
397
+
398
+ // Internal recursive comparison function for `_.isEqual`.
399
+ function deepEq(a, b, aStack, bStack) {
400
+ // Unwrap any wrapped objects.
401
+ if (a instanceof _$1) a = a._wrapped;
402
+ if (b instanceof _$1) b = b._wrapped;
403
+ // Compare `[[Class]]` names.
404
+ var className = toString.call(a);
405
+ if (className !== toString.call(b)) return false;
406
+ // Work around a bug in IE 10 - Edge 13.
407
+ if (hasStringTagBug && className == '[object Object]' && isDataView$1(a)) {
408
+ if (!isDataView$1(b)) return false;
409
+ className = tagDataView;
410
+ }
411
+ switch (className) {
412
+ // These types are compared by value.
413
+ case '[object RegExp]':
414
+ // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i')
415
+ case '[object String]':
416
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
417
+ // equivalent to `new String("5")`.
418
+ return '' + a === '' + b;
419
+ case '[object Number]':
420
+ // `NaN`s are equivalent, but non-reflexive.
421
+ // Object(NaN) is equivalent to NaN.
422
+ if (+a !== +a) return +b !== +b;
423
+ // An `egal` comparison is performed for other numeric values.
424
+ return +a === 0 ? 1 / +a === 1 / b : +a === +b;
425
+ case '[object Date]':
426
+ case '[object Boolean]':
427
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
428
+ // millisecond representations. Note that invalid dates with millisecond representations
429
+ // of `NaN` are not equivalent.
430
+ return +a === +b;
431
+ case '[object Symbol]':
432
+ return SymbolProto.valueOf.call(a) === SymbolProto.valueOf.call(b);
433
+ case '[object ArrayBuffer]':
434
+ case tagDataView:
435
+ // Coerce to typed array so we can fall through.
436
+ return deepEq(toBufferView(a), toBufferView(b), aStack, bStack);
437
+ }
438
+
439
+ var areArrays = className === '[object Array]';
440
+ if (!areArrays && isTypedArray$1(a)) {
441
+ var byteLength = getByteLength(a);
442
+ if (byteLength !== getByteLength(b)) return false;
443
+ if (a.buffer === b.buffer && a.byteOffset === b.byteOffset) return true;
444
+ areArrays = true;
445
+ }
446
+ if (!areArrays) {
447
+ if (typeof a != 'object' || typeof b != 'object') return false;
448
+
449
+ // Objects with different constructors are not equivalent, but `Object`s or `Array`s
450
+ // from different frames are.
451
+ var aCtor = a.constructor, bCtor = b.constructor;
452
+ if (aCtor !== bCtor && !(isFunction$1(aCtor) && aCtor instanceof aCtor &&
453
+ isFunction$1(bCtor) && bCtor instanceof bCtor)
454
+ && ('constructor' in a && 'constructor' in b)) {
455
+ return false;
456
+ }
457
+ }
458
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
459
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
460
+
461
+ // Initializing stack of traversed objects.
462
+ // It's done here since we only need them for objects and arrays comparison.
463
+ aStack = aStack || [];
464
+ bStack = bStack || [];
465
+ var length = aStack.length;
466
+ while (length--) {
467
+ // Linear search. Performance is inversely proportional to the number of
468
+ // unique nested structures.
469
+ if (aStack[length] === a) return bStack[length] === b;
470
+ }
471
+
472
+ // Add the first object to the stack of traversed objects.
473
+ aStack.push(a);
474
+ bStack.push(b);
475
+
476
+ // Recursively compare objects and arrays.
477
+ if (areArrays) {
478
+ // Compare array lengths to determine if a deep comparison is necessary.
479
+ length = a.length;
480
+ if (length !== b.length) return false;
481
+ // Deep compare the contents, ignoring non-numeric properties.
482
+ while (length--) {
483
+ if (!eq(a[length], b[length], aStack, bStack)) return false;
484
+ }
485
+ } else {
486
+ // Deep compare objects.
487
+ var _keys = keys(a), key;
488
+ length = _keys.length;
489
+ // Ensure that both objects contain the same number of properties before comparing deep equality.
490
+ if (keys(b).length !== length) return false;
491
+ while (length--) {
492
+ // Deep compare each member
493
+ key = _keys[length];
494
+ if (!(has$1(b, key) && eq(a[key], b[key], aStack, bStack))) return false;
495
+ }
496
+ }
497
+ // Remove the first object from the stack of traversed objects.
498
+ aStack.pop();
499
+ bStack.pop();
500
+ return true;
501
+ }
502
+
503
+ // Perform a deep comparison to check if two objects are equal.
504
+ function isEqual(a, b) {
505
+ return eq(a, b);
506
+ }
507
+
508
+ // Retrieve all the enumerable property names of an object.
509
+ function allKeys(obj) {
510
+ if (!isObject(obj)) return [];
511
+ var keys = [];
512
+ for (var key in obj) keys.push(key);
513
+ // Ahem, IE < 9.
514
+ if (hasEnumBug) collectNonEnumProps(obj, keys);
515
+ return keys;
516
+ }
517
+
518
+ // Since the regular `Object.prototype.toString` type tests don't work for
519
+ // some types in IE 11, we use a fingerprinting heuristic instead, based
520
+ // on the methods. It's not great, but it's the best we got.
521
+ // The fingerprint method lists are defined below.
522
+ function ie11fingerprint(methods) {
523
+ var length = getLength(methods);
524
+ return function(obj) {
525
+ if (obj == null) return false;
526
+ // `Map`, `WeakMap` and `Set` have no enumerable keys.
527
+ var keys = allKeys(obj);
528
+ if (getLength(keys)) return false;
529
+ for (var i = 0; i < length; i++) {
530
+ if (!isFunction$1(obj[methods[i]])) return false;
531
+ }
532
+ // If we are testing against `WeakMap`, we need to ensure that
533
+ // `obj` doesn't have a `forEach` method in order to distinguish
534
+ // it from a regular `Map`.
535
+ return methods !== weakMapMethods || !isFunction$1(obj[forEachName]);
536
+ };
537
+ }
538
+
539
+ // In the interest of compact minification, we write
540
+ // each string in the fingerprints only once.
541
+ var forEachName = 'forEach',
542
+ hasName = 'has',
543
+ commonInit = ['clear', 'delete'],
544
+ mapTail = ['get', hasName, 'set'];
545
+
546
+ // `Map`, `WeakMap` and `Set` each have slightly different
547
+ // combinations of the above sublists.
548
+ var mapMethods = commonInit.concat(forEachName, mapTail),
549
+ weakMapMethods = commonInit.concat(mapTail),
550
+ setMethods = ['add'].concat(commonInit, forEachName, hasName);
551
+
552
+ var isMap = isIE11 ? ie11fingerprint(mapMethods) : tagTester('Map');
553
+
554
+ var isWeakMap = isIE11 ? ie11fingerprint(weakMapMethods) : tagTester('WeakMap');
555
+
556
+ var isSet = isIE11 ? ie11fingerprint(setMethods) : tagTester('Set');
557
+
558
+ var isWeakSet = tagTester('WeakSet');
559
+
560
+ // Retrieve the values of an object's properties.
561
+ function values(obj) {
562
+ var _keys = keys(obj);
563
+ var length = _keys.length;
564
+ var values = Array(length);
565
+ for (var i = 0; i < length; i++) {
566
+ values[i] = obj[_keys[i]];
567
+ }
568
+ return values;
569
+ }
570
+
571
+ // Convert an object into a list of `[key, value]` pairs.
572
+ // The opposite of `_.object` with one argument.
573
+ function pairs(obj) {
574
+ var _keys = keys(obj);
575
+ var length = _keys.length;
576
+ var pairs = Array(length);
577
+ for (var i = 0; i < length; i++) {
578
+ pairs[i] = [_keys[i], obj[_keys[i]]];
579
+ }
580
+ return pairs;
581
+ }
582
+
583
+ // Invert the keys and values of an object. The values must be serializable.
584
+ function invert(obj) {
585
+ var result = {};
586
+ var _keys = keys(obj);
587
+ for (var i = 0, length = _keys.length; i < length; i++) {
588
+ result[obj[_keys[i]]] = _keys[i];
589
+ }
590
+ return result;
591
+ }
592
+
593
+ // Return a sorted list of the function names available on the object.
594
+ function functions(obj) {
595
+ var names = [];
596
+ for (var key in obj) {
597
+ if (isFunction$1(obj[key])) names.push(key);
598
+ }
599
+ return names.sort();
600
+ }
601
+
602
+ // An internal function for creating assigner functions.
603
+ function createAssigner(keysFunc, defaults) {
604
+ return function(obj) {
605
+ var length = arguments.length;
606
+ if (defaults) obj = Object(obj);
607
+ if (length < 2 || obj == null) return obj;
608
+ for (var index = 1; index < length; index++) {
609
+ var source = arguments[index],
610
+ keys = keysFunc(source),
611
+ l = keys.length;
612
+ for (var i = 0; i < l; i++) {
613
+ var key = keys[i];
614
+ if (!defaults || obj[key] === void 0) obj[key] = source[key];
615
+ }
616
+ }
617
+ return obj;
618
+ };
619
+ }
620
+
621
+ // Extend a given object with all the properties in passed-in object(s).
622
+ var extend = createAssigner(allKeys);
623
+
624
+ // Assigns a given object with all the own properties in the passed-in
625
+ // object(s).
626
+ // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign)
627
+ var extendOwn = createAssigner(keys);
628
+
629
+ // Fill in a given object with default properties.
630
+ var defaults = createAssigner(allKeys, true);
631
+
632
+ // Create a naked function reference for surrogate-prototype-swapping.
633
+ function ctor() {
634
+ return function(){};
635
+ }
636
+
637
+ // An internal function for creating a new object that inherits from another.
638
+ function baseCreate(prototype) {
639
+ if (!isObject(prototype)) return {};
640
+ if (nativeCreate) return nativeCreate(prototype);
641
+ var Ctor = ctor();
642
+ Ctor.prototype = prototype;
643
+ var result = new Ctor;
644
+ Ctor.prototype = null;
645
+ return result;
646
+ }
647
+
648
+ // Creates an object that inherits from the given prototype object.
649
+ // If additional properties are provided then they will be added to the
650
+ // created object.
651
+ function create(prototype, props) {
652
+ var result = baseCreate(prototype);
653
+ if (props) extendOwn(result, props);
654
+ return result;
655
+ }
656
+
657
+ // Create a (shallow-cloned) duplicate of an object.
658
+ function clone(obj) {
659
+ if (!isObject(obj)) return obj;
660
+ return isArray(obj) ? obj.slice() : extend({}, obj);
661
+ }
662
+
663
+ // Invokes `interceptor` with the `obj` and then returns `obj`.
664
+ // The primary purpose of this method is to "tap into" a method chain, in
665
+ // order to perform operations on intermediate results within the chain.
666
+ function tap(obj, interceptor) {
667
+ interceptor(obj);
668
+ return obj;
669
+ }
670
+
671
+ // Normalize a (deep) property `path` to array.
672
+ // Like `_.iteratee`, this function can be customized.
673
+ function toPath$1(path) {
674
+ return isArray(path) ? path : [path];
675
+ }
676
+ _$1.toPath = toPath$1;
677
+
678
+ // Internal wrapper for `_.toPath` to enable minification.
679
+ // Similar to `cb` for `_.iteratee`.
680
+ function toPath(path) {
681
+ return _$1.toPath(path);
682
+ }
683
+
684
+ // Internal function to obtain a nested property in `obj` along `path`.
685
+ function deepGet(obj, path) {
686
+ var length = path.length;
687
+ for (var i = 0; i < length; i++) {
688
+ if (obj == null) return void 0;
689
+ obj = obj[path[i]];
690
+ }
691
+ return length ? obj : void 0;
692
+ }
693
+
694
+ // Get the value of the (deep) property on `path` from `object`.
695
+ // If any property in `path` does not exist or if the value is
696
+ // `undefined`, return `defaultValue` instead.
697
+ // The `path` is normalized through `_.toPath`.
698
+ function get(object, path, defaultValue) {
699
+ var value = deepGet(object, toPath(path));
700
+ return isUndefined(value) ? defaultValue : value;
701
+ }
702
+
703
+ // Shortcut function for checking if an object has a given property directly on
704
+ // itself (in other words, not on a prototype). Unlike the internal `has`
705
+ // function, this public version can also traverse nested properties.
706
+ function has(obj, path) {
707
+ path = toPath(path);
708
+ var length = path.length;
709
+ for (var i = 0; i < length; i++) {
710
+ var key = path[i];
711
+ if (!has$1(obj, key)) return false;
712
+ obj = obj[key];
713
+ }
714
+ return !!length;
715
+ }
716
+
717
+ // Keep the identity function around for default iteratees.
718
+ function identity(value) {
719
+ return value;
720
+ }
721
+
722
+ // Returns a predicate for checking whether an object has a given set of
723
+ // `key:value` pairs.
724
+ function matcher(attrs) {
725
+ attrs = extendOwn({}, attrs);
726
+ return function(obj) {
727
+ return isMatch(obj, attrs);
728
+ };
729
+ }
730
+
731
+ // Creates a function that, when passed an object, will traverse that object’s
732
+ // properties down the given `path`, specified as an array of keys or indices.
733
+ function property(path) {
734
+ path = toPath(path);
735
+ return function(obj) {
736
+ return deepGet(obj, path);
737
+ };
738
+ }
739
+
740
+ // Internal function that returns an efficient (for current engines) version
741
+ // of the passed-in callback, to be repeatedly applied in other Underscore
742
+ // functions.
743
+ function optimizeCb(func, context, argCount) {
744
+ if (context === void 0) return func;
745
+ switch (argCount == null ? 3 : argCount) {
746
+ case 1: return function(value) {
747
+ return func.call(context, value);
748
+ };
749
+ // The 2-argument case is omitted because we’re not using it.
750
+ case 3: return function(value, index, collection) {
751
+ return func.call(context, value, index, collection);
752
+ };
753
+ case 4: return function(accumulator, value, index, collection) {
754
+ return func.call(context, accumulator, value, index, collection);
755
+ };
756
+ }
757
+ return function() {
758
+ return func.apply(context, arguments);
759
+ };
760
+ }
761
+
762
+ // An internal function to generate callbacks that can be applied to each
763
+ // element in a collection, returning the desired result — either `_.identity`,
764
+ // an arbitrary callback, a property matcher, or a property accessor.
765
+ function baseIteratee(value, context, argCount) {
766
+ if (value == null) return identity;
767
+ if (isFunction$1(value)) return optimizeCb(value, context, argCount);
768
+ if (isObject(value) && !isArray(value)) return matcher(value);
769
+ return property(value);
770
+ }
771
+
772
+ // External wrapper for our callback generator. Users may customize
773
+ // `_.iteratee` if they want additional predicate/iteratee shorthand styles.
774
+ // This abstraction hides the internal-only `argCount` argument.
775
+ function iteratee(value, context) {
776
+ return baseIteratee(value, context, Infinity);
777
+ }
778
+ _$1.iteratee = iteratee;
779
+
780
+ // The function we call internally to generate a callback. It invokes
781
+ // `_.iteratee` if overridden, otherwise `baseIteratee`.
782
+ function cb(value, context, argCount) {
783
+ if (_$1.iteratee !== iteratee) return _$1.iteratee(value, context);
784
+ return baseIteratee(value, context, argCount);
785
+ }
786
+
787
+ // Returns the results of applying the `iteratee` to each element of `obj`.
788
+ // In contrast to `_.map` it returns an object.
789
+ function mapObject$1(obj, iteratee, context) {
790
+ iteratee = cb(iteratee, context);
791
+ var _keys = keys(obj),
792
+ length = _keys.length,
793
+ results = {};
794
+ for (var index = 0; index < length; index++) {
795
+ var currentKey = _keys[index];
796
+ results[currentKey] = iteratee(obj[currentKey], currentKey, obj);
797
+ }
798
+ return results;
799
+ }
800
+
801
+ // Predicate-generating function. Often useful outside of Underscore.
802
+ function noop(){}
803
+
804
+ // Generates a function for a given object that returns a given property.
805
+ function propertyOf(obj) {
806
+ if (obj == null) return noop;
807
+ return function(path) {
808
+ return get(obj, path);
809
+ };
810
+ }
811
+
812
+ // Run a function **n** times.
813
+ function times(n, iteratee, context) {
814
+ var accum = Array(Math.max(0, n));
815
+ iteratee = optimizeCb(iteratee, context, 1);
816
+ for (var i = 0; i < n; i++) accum[i] = iteratee(i);
817
+ return accum;
818
+ }
819
+
820
+ // Return a random integer between `min` and `max` (inclusive).
821
+ function random(min, max) {
822
+ if (max == null) {
823
+ max = min;
824
+ min = 0;
825
+ }
826
+ return min + Math.floor(Math.random() * (max - min + 1));
827
+ }
828
+
829
+ // A (possibly faster) way to get the current timestamp as an integer.
830
+ var now = Date.now || function() {
831
+ return new Date().getTime();
832
+ };
833
+
834
+ // Internal helper to generate functions for escaping and unescaping strings
835
+ // to/from HTML interpolation.
836
+ function createEscaper(map) {
837
+ var escaper = function(match) {
838
+ return map[match];
839
+ };
840
+ // Regexes for identifying a key that needs to be escaped.
841
+ var source = '(?:' + keys(map).join('|') + ')';
842
+ var testRegexp = RegExp(source);
843
+ var replaceRegexp = RegExp(source, 'g');
844
+ return function(string) {
845
+ string = string == null ? '' : '' + string;
846
+ return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string;
847
+ };
848
+ }
849
+
850
+ // Internal list of HTML entities for escaping.
851
+ var escapeMap = {
852
+ '&': '&amp;',
853
+ '<': '&lt;',
854
+ '>': '&gt;',
855
+ '"': '&quot;',
856
+ "'": '&#x27;',
857
+ '`': '&#x60;'
858
+ };
859
+
860
+ // Function for escaping strings to HTML interpolation.
861
+ var escape = createEscaper(escapeMap);
862
+
863
+ // Internal list of HTML entities for unescaping.
864
+ var unescapeMap = invert(escapeMap);
865
+
866
+ // Function for unescaping strings from HTML interpolation.
867
+ var unescape = createEscaper(unescapeMap);
868
+
869
+ // By default, Underscore uses ERB-style template delimiters. Change the
870
+ // following template settings to use alternative delimiters.
871
+ var templateSettings = _$1.templateSettings = {
872
+ evaluate: /<%([\s\S]+?)%>/g,
873
+ interpolate: /<%=([\s\S]+?)%>/g,
874
+ escape: /<%-([\s\S]+?)%>/g
875
+ };
876
+
877
+ // When customizing `_.templateSettings`, if you don't want to define an
878
+ // interpolation, evaluation or escaping regex, we need one that is
879
+ // guaranteed not to match.
880
+ var noMatch = /(.)^/;
881
+
882
+ // Certain characters need to be escaped so that they can be put into a
883
+ // string literal.
884
+ var escapes = {
885
+ "'": "'",
886
+ '\\': '\\',
887
+ '\r': 'r',
888
+ '\n': 'n',
889
+ '\u2028': 'u2028',
890
+ '\u2029': 'u2029'
891
+ };
892
+
893
+ var escapeRegExp = /\\|'|\r|\n|\u2028|\u2029/g;
894
+
895
+ function escapeChar(match) {
896
+ return '\\' + escapes[match];
897
+ }
898
+
899
+ // In order to prevent third-party code injection through
900
+ // `_.templateSettings.variable`, we test it against the following regular
901
+ // expression. It is intentionally a bit more liberal than just matching valid
902
+ // identifiers, but still prevents possible loopholes through defaults or
903
+ // destructuring assignment.
904
+ var bareIdentifier = /^\s*(\w|\$)+\s*$/;
905
+
906
+ // JavaScript micro-templating, similar to John Resig's implementation.
907
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
908
+ // and correctly escapes quotes within interpolated code.
909
+ // NB: `oldSettings` only exists for backwards compatibility.
910
+ function template(text, settings, oldSettings) {
911
+ if (!settings && oldSettings) settings = oldSettings;
912
+ settings = defaults({}, settings, _$1.templateSettings);
913
+
914
+ // Combine delimiters into one regular expression via alternation.
915
+ var matcher = RegExp([
916
+ (settings.escape || noMatch).source,
917
+ (settings.interpolate || noMatch).source,
918
+ (settings.evaluate || noMatch).source
919
+ ].join('|') + '|$', 'g');
920
+
921
+ // Compile the template source, escaping string literals appropriately.
922
+ var index = 0;
923
+ var source = "__p+='";
924
+ text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
925
+ source += text.slice(index, offset).replace(escapeRegExp, escapeChar);
926
+ index = offset + match.length;
927
+
928
+ if (escape) {
929
+ source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'";
930
+ } else if (interpolate) {
931
+ source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
932
+ } else if (evaluate) {
933
+ source += "';\n" + evaluate + "\n__p+='";
934
+ }
935
+
936
+ // Adobe VMs need the match returned to produce the correct offset.
937
+ return match;
938
+ });
939
+ source += "';\n";
940
+
941
+ var argument = settings.variable;
942
+ if (argument) {
943
+ // Insure against third-party code injection. (CVE-2021-23358)
944
+ if (!bareIdentifier.test(argument)) throw new Error(
945
+ 'variable is not a bare identifier: ' + argument
946
+ );
947
+ } else {
948
+ // If a variable is not specified, place data values in local scope.
949
+ source = 'with(obj||{}){\n' + source + '}\n';
950
+ argument = 'obj';
951
+ }
952
+
953
+ source = "var __t,__p='',__j=Array.prototype.join," +
954
+ "print=function(){__p+=__j.call(arguments,'');};\n" +
955
+ source + 'return __p;\n';
956
+
957
+ var render;
958
+ try {
959
+ render = new Function(argument, '_', source);
960
+ } catch (e) {
961
+ e.source = source;
962
+ throw e;
963
+ }
964
+
965
+ var template = function(data) {
966
+ return render.call(this, data, _$1);
967
+ };
968
+
969
+ // Provide the compiled source as a convenience for precompilation.
970
+ template.source = 'function(' + argument + '){\n' + source + '}';
971
+
972
+ return template;
973
+ }
974
+
975
+ // Traverses the children of `obj` along `path`. If a child is a function, it
976
+ // is invoked with its parent as context. Returns the value of the final
977
+ // child, or `fallback` if any child is undefined.
978
+ function result(obj, path, fallback) {
979
+ path = toPath(path);
980
+ var length = path.length;
981
+ if (!length) {
982
+ return isFunction$1(fallback) ? fallback.call(obj) : fallback;
983
+ }
984
+ for (var i = 0; i < length; i++) {
985
+ var prop = obj == null ? void 0 : obj[path[i]];
986
+ if (prop === void 0) {
987
+ prop = fallback;
988
+ i = length; // Ensure we don't continue iterating.
989
+ }
990
+ obj = isFunction$1(prop) ? prop.call(obj) : prop;
991
+ }
992
+ return obj;
993
+ }
994
+
995
+ // Generate a unique integer id (unique within the entire client session).
996
+ // Useful for temporary DOM ids.
997
+ var idCounter = 0;
998
+ function uniqueId(prefix) {
999
+ var id = ++idCounter + '';
1000
+ return prefix ? prefix + id : id;
1001
+ }
1002
+
1003
+ // Start chaining a wrapped Underscore object.
1004
+ function chain(obj) {
1005
+ var instance = _$1(obj);
1006
+ instance._chain = true;
1007
+ return instance;
1008
+ }
1009
+
1010
+ // Internal function to execute `sourceFunc` bound to `context` with optional
1011
+ // `args`. Determines whether to execute a function as a constructor or as a
1012
+ // normal function.
1013
+ function executeBound(sourceFunc, boundFunc, context, callingContext, args) {
1014
+ if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args);
1015
+ var self = baseCreate(sourceFunc.prototype);
1016
+ var result = sourceFunc.apply(self, args);
1017
+ if (isObject(result)) return result;
1018
+ return self;
1019
+ }
1020
+
1021
+ // Partially apply a function by creating a version that has had some of its
1022
+ // arguments pre-filled, without changing its dynamic `this` context. `_` acts
1023
+ // as a placeholder by default, allowing any combination of arguments to be
1024
+ // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument.
1025
+ var partial = restArguments(function(func, boundArgs) {
1026
+ var placeholder = partial.placeholder;
1027
+ var bound = function() {
1028
+ var position = 0, length = boundArgs.length;
1029
+ var args = Array(length);
1030
+ for (var i = 0; i < length; i++) {
1031
+ args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i];
1032
+ }
1033
+ while (position < arguments.length) args.push(arguments[position++]);
1034
+ return executeBound(func, bound, this, this, args);
1035
+ };
1036
+ return bound;
1037
+ });
1038
+
1039
+ partial.placeholder = _$1;
1040
+
1041
+ // Create a function bound to a given object (assigning `this`, and arguments,
1042
+ // optionally).
1043
+ var bind = restArguments(function(func, context, args) {
1044
+ if (!isFunction$1(func)) throw new TypeError('Bind must be called on a function');
1045
+ var bound = restArguments(function(callArgs) {
1046
+ return executeBound(func, bound, context, this, args.concat(callArgs));
1047
+ });
1048
+ return bound;
1049
+ });
1050
+
1051
+ // Internal helper for collection methods to determine whether a collection
1052
+ // should be iterated as an array or as an object.
1053
+ // Related: https://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength
1054
+ // Avoids a very nasty iOS 8 JIT bug on ARM-64. #2094
1055
+ var isArrayLike = createSizePropertyCheck(getLength);
1056
+
1057
+ // Internal implementation of a recursive `flatten` function.
1058
+ function flatten$1(input, depth, strict, output) {
1059
+ output = output || [];
1060
+ if (!depth && depth !== 0) {
1061
+ depth = Infinity;
1062
+ } else if (depth <= 0) {
1063
+ return output.concat(input);
1064
+ }
1065
+ var idx = output.length;
1066
+ for (var i = 0, length = getLength(input); i < length; i++) {
1067
+ var value = input[i];
1068
+ if (isArrayLike(value) && (isArray(value) || isArguments$1(value))) {
1069
+ // Flatten current level of array or arguments object.
1070
+ if (depth > 1) {
1071
+ flatten$1(value, depth - 1, strict, output);
1072
+ idx = output.length;
1073
+ } else {
1074
+ var j = 0, len = value.length;
1075
+ while (j < len) output[idx++] = value[j++];
1076
+ }
1077
+ } else if (!strict) {
1078
+ output[idx++] = value;
1079
+ }
1080
+ }
1081
+ return output;
1082
+ }
1083
+
1084
+ // Bind a number of an object's methods to that object. Remaining arguments
1085
+ // are the method names to be bound. Useful for ensuring that all callbacks
1086
+ // defined on an object belong to it.
1087
+ var bindAll = restArguments(function(obj, keys) {
1088
+ keys = flatten$1(keys, false, false);
1089
+ var index = keys.length;
1090
+ if (index < 1) throw new Error('bindAll must be passed function names');
1091
+ while (index--) {
1092
+ var key = keys[index];
1093
+ obj[key] = bind(obj[key], obj);
1094
+ }
1095
+ return obj;
1096
+ });
1097
+
1098
+ // Memoize an expensive function by storing its results.
1099
+ function memoize(func, hasher) {
1100
+ var memoize = function(key) {
1101
+ var cache = memoize.cache;
1102
+ var address = '' + (hasher ? hasher.apply(this, arguments) : key);
1103
+ if (!has$1(cache, address)) cache[address] = func.apply(this, arguments);
1104
+ return cache[address];
1105
+ };
1106
+ memoize.cache = {};
1107
+ return memoize;
1108
+ }
1109
+
1110
+ // Delays a function for the given number of milliseconds, and then calls
1111
+ // it with the arguments supplied.
1112
+ var delay = restArguments(function(func, wait, args) {
1113
+ return setTimeout(function() {
1114
+ return func.apply(null, args);
1115
+ }, wait);
1116
+ });
1117
+
1118
+ // Defers a function, scheduling it to run after the current call stack has
1119
+ // cleared.
1120
+ var defer = partial(delay, _$1, 1);
1121
+
1122
+ // Returns a function, that, when invoked, will only be triggered at most once
1123
+ // during a given window of time. Normally, the throttled function will run
1124
+ // as much as it can, without ever going more than once per `wait` duration;
1125
+ // but if you'd like to disable the execution on the leading edge, pass
1126
+ // `{leading: false}`. To disable execution on the trailing edge, ditto.
1127
+ function throttle(func, wait, options) {
1128
+ var timeout, context, args, result;
1129
+ var previous = 0;
1130
+ if (!options) options = {};
1131
+
1132
+ var later = function() {
1133
+ previous = options.leading === false ? 0 : now();
1134
+ timeout = null;
1135
+ result = func.apply(context, args);
1136
+ if (!timeout) context = args = null;
1137
+ };
1138
+
1139
+ var throttled = function() {
1140
+ var _now = now();
1141
+ if (!previous && options.leading === false) previous = _now;
1142
+ var remaining = wait - (_now - previous);
1143
+ context = this;
1144
+ args = arguments;
1145
+ if (remaining <= 0 || remaining > wait) {
1146
+ if (timeout) {
1147
+ clearTimeout(timeout);
1148
+ timeout = null;
1149
+ }
1150
+ previous = _now;
1151
+ result = func.apply(context, args);
1152
+ if (!timeout) context = args = null;
1153
+ } else if (!timeout && options.trailing !== false) {
1154
+ timeout = setTimeout(later, remaining);
1155
+ }
1156
+ return result;
1157
+ };
1158
+
1159
+ throttled.cancel = function() {
1160
+ clearTimeout(timeout);
1161
+ previous = 0;
1162
+ timeout = context = args = null;
1163
+ };
1164
+
1165
+ return throttled;
1166
+ }
1167
+
1168
+ // When a sequence of calls of the returned function ends, the argument
1169
+ // function is triggered. The end of a sequence is defined by the `wait`
1170
+ // parameter. If `immediate` is passed, the argument function will be
1171
+ // triggered at the beginning of the sequence instead of at the end.
1172
+ function debounce(func, wait, immediate) {
1173
+ var timeout, previous, args, result, context;
1174
+
1175
+ var later = function() {
1176
+ var passed = now() - previous;
1177
+ if (wait > passed) {
1178
+ timeout = setTimeout(later, wait - passed);
1179
+ } else {
1180
+ timeout = null;
1181
+ if (!immediate) result = func.apply(context, args);
1182
+ // This check is needed because `func` can recursively invoke `debounced`.
1183
+ if (!timeout) args = context = null;
1184
+ }
1185
+ };
1186
+
1187
+ var debounced = restArguments(function(_args) {
1188
+ context = this;
1189
+ args = _args;
1190
+ previous = now();
1191
+ if (!timeout) {
1192
+ timeout = setTimeout(later, wait);
1193
+ if (immediate) result = func.apply(context, args);
1194
+ }
1195
+ return result;
1196
+ });
1197
+
1198
+ debounced.cancel = function() {
1199
+ clearTimeout(timeout);
1200
+ timeout = args = context = null;
1201
+ };
1202
+
1203
+ return debounced;
1204
+ }
1205
+
1206
+ // Returns the first function passed as an argument to the second,
1207
+ // allowing you to adjust arguments, run code before and after, and
1208
+ // conditionally execute the original function.
1209
+ function wrap(func, wrapper) {
1210
+ return partial(wrapper, func);
1211
+ }
1212
+
1213
+ // Returns a negated version of the passed-in predicate.
1214
+ function negate(predicate) {
1215
+ return function() {
1216
+ return !predicate.apply(this, arguments);
1217
+ };
1218
+ }
1219
+
1220
+ // Returns a function that is the composition of a list of functions, each
1221
+ // consuming the return value of the function that follows.
1222
+ function compose() {
1223
+ var args = arguments;
1224
+ var start = args.length - 1;
1225
+ return function() {
1226
+ var i = start;
1227
+ var result = args[start].apply(this, arguments);
1228
+ while (i--) result = args[i].call(this, result);
1229
+ return result;
1230
+ };
1231
+ }
1232
+
1233
+ // Returns a function that will only be executed on and after the Nth call.
1234
+ function after(times, func) {
1235
+ return function() {
1236
+ if (--times < 1) {
1237
+ return func.apply(this, arguments);
1238
+ }
1239
+ };
1240
+ }
1241
+
1242
+ // Returns a function that will only be executed up to (but not including) the
1243
+ // Nth call.
1244
+ function before(times, func) {
1245
+ var memo;
1246
+ return function() {
1247
+ if (--times > 0) {
1248
+ memo = func.apply(this, arguments);
1249
+ }
1250
+ if (times <= 1) func = null;
1251
+ return memo;
1252
+ };
1253
+ }
1254
+
1255
+ // Returns a function that will be executed at most one time, no matter how
1256
+ // often you call it. Useful for lazy initialization.
1257
+ var once = partial(before, 2);
1258
+
1259
+ // Returns the first key on an object that passes a truth test.
1260
+ function findKey(obj, predicate, context) {
1261
+ predicate = cb(predicate, context);
1262
+ var _keys = keys(obj), key;
1263
+ for (var i = 0, length = _keys.length; i < length; i++) {
1264
+ key = _keys[i];
1265
+ if (predicate(obj[key], key, obj)) return key;
1266
+ }
1267
+ }
1268
+
1269
+ // Internal function to generate `_.findIndex` and `_.findLastIndex`.
1270
+ function createPredicateIndexFinder(dir) {
1271
+ return function(array, predicate, context) {
1272
+ predicate = cb(predicate, context);
1273
+ var length = getLength(array);
1274
+ var index = dir > 0 ? 0 : length - 1;
1275
+ for (; index >= 0 && index < length; index += dir) {
1276
+ if (predicate(array[index], index, array)) return index;
1277
+ }
1278
+ return -1;
1279
+ };
1280
+ }
1281
+
1282
+ // Returns the first index on an array-like that passes a truth test.
1283
+ var findIndex = createPredicateIndexFinder(1);
1284
+
1285
+ // Returns the last index on an array-like that passes a truth test.
1286
+ var findLastIndex = createPredicateIndexFinder(-1);
1287
+
1288
+ // Use a comparator function to figure out the smallest index at which
1289
+ // an object should be inserted so as to maintain order. Uses binary search.
1290
+ function sortedIndex(array, obj, iteratee, context) {
1291
+ iteratee = cb(iteratee, context, 1);
1292
+ var value = iteratee(obj);
1293
+ var low = 0, high = getLength(array);
1294
+ while (low < high) {
1295
+ var mid = Math.floor((low + high) / 2);
1296
+ if (iteratee(array[mid]) < value) low = mid + 1; else high = mid;
1297
+ }
1298
+ return low;
1299
+ }
1300
+
1301
+ // Internal function to generate the `_.indexOf` and `_.lastIndexOf` functions.
1302
+ function createIndexFinder(dir, predicateFind, sortedIndex) {
1303
+ return function(array, item, idx) {
1304
+ var i = 0, length = getLength(array);
1305
+ if (typeof idx == 'number') {
1306
+ if (dir > 0) {
1307
+ i = idx >= 0 ? idx : Math.max(idx + length, i);
1308
+ } else {
1309
+ length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1;
1310
+ }
1311
+ } else if (sortedIndex && idx && length) {
1312
+ idx = sortedIndex(array, item);
1313
+ return array[idx] === item ? idx : -1;
1314
+ }
1315
+ if (item !== item) {
1316
+ idx = predicateFind(slice.call(array, i, length), isNaN$1);
1317
+ return idx >= 0 ? idx + i : -1;
1318
+ }
1319
+ for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) {
1320
+ if (array[idx] === item) return idx;
1321
+ }
1322
+ return -1;
1323
+ };
1324
+ }
1325
+
1326
+ // Return the position of the first occurrence of an item in an array,
1327
+ // or -1 if the item is not included in the array.
1328
+ // If the array is large and already in sort order, pass `true`
1329
+ // for **isSorted** to use binary search.
1330
+ var indexOf = createIndexFinder(1, findIndex, sortedIndex);
1331
+
1332
+ // Return the position of the last occurrence of an item in an array,
1333
+ // or -1 if the item is not included in the array.
1334
+ var lastIndexOf = createIndexFinder(-1, findLastIndex);
1335
+
1336
+ // Return the first value which passes a truth test.
1337
+ function find(obj, predicate, context) {
1338
+ var keyFinder = isArrayLike(obj) ? findIndex : findKey;
1339
+ var key = keyFinder(obj, predicate, context);
1340
+ if (key !== void 0 && key !== -1) return obj[key];
1341
+ }
1342
+
1343
+ // Convenience version of a common use case of `_.find`: getting the first
1344
+ // object containing specific `key:value` pairs.
1345
+ function findWhere(obj, attrs) {
1346
+ return find(obj, matcher(attrs));
1347
+ }
1348
+
1349
+ // The cornerstone for collection functions, an `each`
1350
+ // implementation, aka `forEach`.
1351
+ // Handles raw objects in addition to array-likes. Treats all
1352
+ // sparse array-likes as if they were dense.
1353
+ function each(obj, iteratee, context) {
1354
+ iteratee = optimizeCb(iteratee, context);
1355
+ var i, length;
1356
+ if (isArrayLike(obj)) {
1357
+ for (i = 0, length = obj.length; i < length; i++) {
1358
+ iteratee(obj[i], i, obj);
1359
+ }
1360
+ } else {
1361
+ var _keys = keys(obj);
1362
+ for (i = 0, length = _keys.length; i < length; i++) {
1363
+ iteratee(obj[_keys[i]], _keys[i], obj);
1364
+ }
1365
+ }
1366
+ return obj;
1367
+ }
1368
+
1369
+ // Return the results of applying the iteratee to each element.
1370
+ function map(obj, iteratee, context) {
1371
+ iteratee = cb(iteratee, context);
1372
+ var _keys = !isArrayLike(obj) && keys(obj),
1373
+ length = (_keys || obj).length,
1374
+ results = Array(length);
1375
+ for (var index = 0; index < length; index++) {
1376
+ var currentKey = _keys ? _keys[index] : index;
1377
+ results[index] = iteratee(obj[currentKey], currentKey, obj);
1378
+ }
1379
+ return results;
1380
+ }
1381
+
1382
+ // Internal helper to create a reducing function, iterating left or right.
1383
+ function createReduce(dir) {
1384
+ // Wrap code that reassigns argument variables in a separate function than
1385
+ // the one that accesses `arguments.length` to avoid a perf hit. (#1991)
1386
+ var reducer = function(obj, iteratee, memo, initial) {
1387
+ var _keys = !isArrayLike(obj) && keys(obj),
1388
+ length = (_keys || obj).length,
1389
+ index = dir > 0 ? 0 : length - 1;
1390
+ if (!initial) {
1391
+ memo = obj[_keys ? _keys[index] : index];
1392
+ index += dir;
1393
+ }
1394
+ for (; index >= 0 && index < length; index += dir) {
1395
+ var currentKey = _keys ? _keys[index] : index;
1396
+ memo = iteratee(memo, obj[currentKey], currentKey, obj);
1397
+ }
1398
+ return memo;
1399
+ };
1400
+
1401
+ return function(obj, iteratee, memo, context) {
1402
+ var initial = arguments.length >= 3;
1403
+ return reducer(obj, optimizeCb(iteratee, context, 4), memo, initial);
1404
+ };
1405
+ }
1406
+
1407
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
1408
+ // or `foldl`.
1409
+ var reduce = createReduce(1);
1410
+
1411
+ // The right-associative version of reduce, also known as `foldr`.
1412
+ var reduceRight = createReduce(-1);
1413
+
1414
+ // Return all the elements that pass a truth test.
1415
+ function filter(obj, predicate, context) {
1416
+ var results = [];
1417
+ predicate = cb(predicate, context);
1418
+ each(obj, function(value, index, list) {
1419
+ if (predicate(value, index, list)) results.push(value);
1420
+ });
1421
+ return results;
1422
+ }
1423
+
1424
+ // Return all the elements for which a truth test fails.
1425
+ function reject(obj, predicate, context) {
1426
+ return filter(obj, negate(cb(predicate)), context);
1427
+ }
1428
+
1429
+ // Determine whether all of the elements pass a truth test.
1430
+ function every(obj, predicate, context) {
1431
+ predicate = cb(predicate, context);
1432
+ var _keys = !isArrayLike(obj) && keys(obj),
1433
+ length = (_keys || obj).length;
1434
+ for (var index = 0; index < length; index++) {
1435
+ var currentKey = _keys ? _keys[index] : index;
1436
+ if (!predicate(obj[currentKey], currentKey, obj)) return false;
1437
+ }
1438
+ return true;
1439
+ }
1440
+
1441
+ // Determine if at least one element in the object passes a truth test.
1442
+ function some(obj, predicate, context) {
1443
+ predicate = cb(predicate, context);
1444
+ var _keys = !isArrayLike(obj) && keys(obj),
1445
+ length = (_keys || obj).length;
1446
+ for (var index = 0; index < length; index++) {
1447
+ var currentKey = _keys ? _keys[index] : index;
1448
+ if (predicate(obj[currentKey], currentKey, obj)) return true;
1449
+ }
1450
+ return false;
1451
+ }
1452
+
1453
+ // Determine if the array or object contains a given item (using `===`).
1454
+ function contains(obj, item, fromIndex, guard) {
1455
+ if (!isArrayLike(obj)) obj = values(obj);
1456
+ if (typeof fromIndex != 'number' || guard) fromIndex = 0;
1457
+ return indexOf(obj, item, fromIndex) >= 0;
1458
+ }
1459
+
1460
+ // Invoke a method (with arguments) on every item in a collection.
1461
+ var invoke = restArguments(function(obj, path, args) {
1462
+ var contextPath, func;
1463
+ if (isFunction$1(path)) {
1464
+ func = path;
1465
+ } else {
1466
+ path = toPath(path);
1467
+ contextPath = path.slice(0, -1);
1468
+ path = path[path.length - 1];
1469
+ }
1470
+ return map(obj, function(context) {
1471
+ var method = func;
1472
+ if (!method) {
1473
+ if (contextPath && contextPath.length) {
1474
+ context = deepGet(context, contextPath);
1475
+ }
1476
+ if (context == null) return void 0;
1477
+ method = context[path];
1478
+ }
1479
+ return method == null ? method : method.apply(context, args);
1480
+ });
1481
+ });
1482
+
1483
+ // Convenience version of a common use case of `_.map`: fetching a property.
1484
+ function pluck$1(obj, key) {
1485
+ return map(obj, property(key));
1486
+ }
1487
+
1488
+ // Convenience version of a common use case of `_.filter`: selecting only
1489
+ // objects containing specific `key:value` pairs.
1490
+ function where(obj, attrs) {
1491
+ return filter(obj, matcher(attrs));
1492
+ }
1493
+
1494
+ // Return the maximum element (or element-based computation).
1495
+ function max(obj, iteratee, context) {
1496
+ var result = -Infinity, lastComputed = -Infinity,
1497
+ value, computed;
1498
+ if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
1499
+ obj = isArrayLike(obj) ? obj : values(obj);
1500
+ for (var i = 0, length = obj.length; i < length; i++) {
1501
+ value = obj[i];
1502
+ if (value != null && value > result) {
1503
+ result = value;
1504
+ }
1505
+ }
1506
+ } else {
1507
+ iteratee = cb(iteratee, context);
1508
+ each(obj, function(v, index, list) {
1509
+ computed = iteratee(v, index, list);
1510
+ if (computed > lastComputed || (computed === -Infinity && result === -Infinity)) {
1511
+ result = v;
1512
+ lastComputed = computed;
1513
+ }
1514
+ });
1515
+ }
1516
+ return result;
1517
+ }
1518
+
1519
+ // Return the minimum element (or element-based computation).
1520
+ function min(obj, iteratee, context) {
1521
+ var result = Infinity, lastComputed = Infinity,
1522
+ value, computed;
1523
+ if (iteratee == null || (typeof iteratee == 'number' && typeof obj[0] != 'object' && obj != null)) {
1524
+ obj = isArrayLike(obj) ? obj : values(obj);
1525
+ for (var i = 0, length = obj.length; i < length; i++) {
1526
+ value = obj[i];
1527
+ if (value != null && value < result) {
1528
+ result = value;
1529
+ }
1530
+ }
1531
+ } else {
1532
+ iteratee = cb(iteratee, context);
1533
+ each(obj, function(v, index, list) {
1534
+ computed = iteratee(v, index, list);
1535
+ if (computed < lastComputed || (computed === Infinity && result === Infinity)) {
1536
+ result = v;
1537
+ lastComputed = computed;
1538
+ }
1539
+ });
1540
+ }
1541
+ return result;
1542
+ }
1543
+
1544
+ // Safely create a real, live array from anything iterable.
1545
+ var reStrSymbol = /[^\ud800-\udfff]|[\ud800-\udbff][\udc00-\udfff]|[\ud800-\udfff]/g;
1546
+ function toArray(obj) {
1547
+ if (!obj) return [];
1548
+ if (isArray(obj)) return slice.call(obj);
1549
+ if (isString(obj)) {
1550
+ // Keep surrogate pair characters together.
1551
+ return obj.match(reStrSymbol);
1552
+ }
1553
+ if (isArrayLike(obj)) return map(obj, identity);
1554
+ return values(obj);
1555
+ }
1556
+
1557
+ // Sample **n** random values from a collection using the modern version of the
1558
+ // [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher–Yates_shuffle).
1559
+ // If **n** is not specified, returns a single random element.
1560
+ // The internal `guard` argument allows it to work with `_.map`.
1561
+ function sample(obj, n, guard) {
1562
+ if (n == null || guard) {
1563
+ if (!isArrayLike(obj)) obj = values(obj);
1564
+ return obj[random(obj.length - 1)];
1565
+ }
1566
+ var sample = toArray(obj);
1567
+ var length = getLength(sample);
1568
+ n = Math.max(Math.min(n, length), 0);
1569
+ var last = length - 1;
1570
+ for (var index = 0; index < n; index++) {
1571
+ var rand = random(index, last);
1572
+ var temp = sample[index];
1573
+ sample[index] = sample[rand];
1574
+ sample[rand] = temp;
1575
+ }
1576
+ return sample.slice(0, n);
1577
+ }
1578
+
1579
+ // Shuffle a collection.
1580
+ function shuffle(obj) {
1581
+ return sample(obj, Infinity);
1582
+ }
1583
+
1584
+ // Sort the object's values by a criterion produced by an iteratee.
1585
+ function sortBy(obj, iteratee, context) {
1586
+ var index = 0;
1587
+ iteratee = cb(iteratee, context);
1588
+ return pluck$1(map(obj, function(value, key, list) {
1589
+ return {
1590
+ value: value,
1591
+ index: index++,
1592
+ criteria: iteratee(value, key, list)
1593
+ };
1594
+ }).sort(function(left, right) {
1595
+ var a = left.criteria;
1596
+ var b = right.criteria;
1597
+ if (a !== b) {
1598
+ if (a > b || a === void 0) return 1;
1599
+ if (a < b || b === void 0) return -1;
1600
+ }
1601
+ return left.index - right.index;
1602
+ }), 'value');
1603
+ }
1604
+
1605
+ // An internal function used for aggregate "group by" operations.
1606
+ function group(behavior, partition) {
1607
+ return function(obj, iteratee, context) {
1608
+ var result = partition ? [[], []] : {};
1609
+ iteratee = cb(iteratee, context);
1610
+ each(obj, function(value, index) {
1611
+ var key = iteratee(value, index, obj);
1612
+ behavior(result, value, key);
1613
+ });
1614
+ return result;
1615
+ };
1616
+ }
1617
+
1618
+ // Groups the object's values by a criterion. Pass either a string attribute
1619
+ // to group by, or a function that returns the criterion.
1620
+ var groupBy = group(function(result, value, key) {
1621
+ if (has$1(result, key)) result[key].push(value); else result[key] = [value];
1622
+ });
1623
+
1624
+ // Indexes the object's values by a criterion, similar to `_.groupBy`, but for
1625
+ // when you know that your index values will be unique.
1626
+ var indexBy = group(function(result, value, key) {
1627
+ result[key] = value;
1628
+ });
1629
+
1630
+ // Counts instances of an object that group by a certain criterion. Pass
1631
+ // either a string attribute to count by, or a function that returns the
1632
+ // criterion.
1633
+ var countBy = group(function(result, value, key) {
1634
+ if (has$1(result, key)) result[key]++; else result[key] = 1;
1635
+ });
1636
+
1637
+ // Split a collection into two arrays: one whose elements all pass the given
1638
+ // truth test, and one whose elements all do not pass the truth test.
1639
+ var partition = group(function(result, value, pass) {
1640
+ result[pass ? 0 : 1].push(value);
1641
+ }, true);
1642
+
1643
+ // Return the number of elements in a collection.
1644
+ function size(obj) {
1645
+ if (obj == null) return 0;
1646
+ return isArrayLike(obj) ? obj.length : keys(obj).length;
1647
+ }
1648
+
1649
+ // Internal `_.pick` helper function to determine whether `key` is an enumerable
1650
+ // property name of `obj`.
1651
+ function keyInObj(value, key, obj) {
1652
+ return key in obj;
1653
+ }
1654
+
1655
+ // Return a copy of the object only containing the allowed properties.
1656
+ var pick = restArguments(function(obj, keys) {
1657
+ var result = {}, iteratee = keys[0];
1658
+ if (obj == null) return result;
1659
+ if (isFunction$1(iteratee)) {
1660
+ if (keys.length > 1) iteratee = optimizeCb(iteratee, keys[1]);
1661
+ keys = allKeys(obj);
1662
+ } else {
1663
+ iteratee = keyInObj;
1664
+ keys = flatten$1(keys, false, false);
1665
+ obj = Object(obj);
1666
+ }
1667
+ for (var i = 0, length = keys.length; i < length; i++) {
1668
+ var key = keys[i];
1669
+ var value = obj[key];
1670
+ if (iteratee(value, key, obj)) result[key] = value;
1671
+ }
1672
+ return result;
1673
+ });
1674
+
1675
+ // Return a copy of the object without the disallowed properties.
1676
+ var omit = restArguments(function(obj, keys) {
1677
+ var iteratee = keys[0], context;
1678
+ if (isFunction$1(iteratee)) {
1679
+ iteratee = negate(iteratee);
1680
+ if (keys.length > 1) context = keys[1];
1681
+ } else {
1682
+ keys = map(flatten$1(keys, false, false), String);
1683
+ iteratee = function(value, key) {
1684
+ return !contains(keys, key);
1685
+ };
1686
+ }
1687
+ return pick(obj, iteratee, context);
1688
+ });
1689
+
1690
+ // Returns everything but the last entry of the array. Especially useful on
1691
+ // the arguments object. Passing **n** will return all the values in
1692
+ // the array, excluding the last N.
1693
+ function initial(array, n, guard) {
1694
+ return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n)));
1695
+ }
1696
+
1697
+ // Get the first element of an array. Passing **n** will return the first N
1698
+ // values in the array. The **guard** check allows it to work with `_.map`.
1699
+ function first(array, n, guard) {
1700
+ if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
1701
+ if (n == null || guard) return array[0];
1702
+ return initial(array, array.length - n);
1703
+ }
1704
+
1705
+ // Returns everything but the first entry of the `array`. Especially useful on
1706
+ // the `arguments` object. Passing an **n** will return the rest N values in the
1707
+ // `array`.
1708
+ function rest(array, n, guard) {
1709
+ return slice.call(array, n == null || guard ? 1 : n);
1710
+ }
1711
+
1712
+ // Get the last element of an array. Passing **n** will return the last N
1713
+ // values in the array.
1714
+ function last(array, n, guard) {
1715
+ if (array == null || array.length < 1) return n == null || guard ? void 0 : [];
1716
+ if (n == null || guard) return array[array.length - 1];
1717
+ return rest(array, Math.max(0, array.length - n));
1718
+ }
1719
+
1720
+ // Trim out all falsy values from an array.
1721
+ function compact(array) {
1722
+ return filter(array, Boolean);
1723
+ }
1724
+
1725
+ // Flatten out an array, either recursively (by default), or up to `depth`.
1726
+ // Passing `true` or `false` as `depth` means `1` or `Infinity`, respectively.
1727
+ function flatten(array, depth) {
1728
+ return flatten$1(array, depth, false);
1729
+ }
1730
+
1731
+ // Take the difference between one array and a number of other arrays.
1732
+ // Only the elements present in just the first array will remain.
1733
+ var difference = restArguments(function(array, rest) {
1734
+ rest = flatten$1(rest, true, true);
1735
+ return filter(array, function(value){
1736
+ return !contains(rest, value);
1737
+ });
1738
+ });
1739
+
1740
+ // Return a version of the array that does not contain the specified value(s).
1741
+ var without = restArguments(function(array, otherArrays) {
1742
+ return difference(array, otherArrays);
1743
+ });
1744
+
1745
+ // Produce a duplicate-free version of the array. If the array has already
1746
+ // been sorted, you have the option of using a faster algorithm.
1747
+ // The faster algorithm will not work with an iteratee if the iteratee
1748
+ // is not a one-to-one function, so providing an iteratee will disable
1749
+ // the faster algorithm.
1750
+ function uniq(array, isSorted, iteratee, context) {
1751
+ if (!isBoolean(isSorted)) {
1752
+ context = iteratee;
1753
+ iteratee = isSorted;
1754
+ isSorted = false;
1755
+ }
1756
+ if (iteratee != null) iteratee = cb(iteratee, context);
1757
+ var result = [];
1758
+ var seen = [];
1759
+ for (var i = 0, length = getLength(array); i < length; i++) {
1760
+ var value = array[i],
1761
+ computed = iteratee ? iteratee(value, i, array) : value;
1762
+ if (isSorted && !iteratee) {
1763
+ if (!i || seen !== computed) result.push(value);
1764
+ seen = computed;
1765
+ } else if (iteratee) {
1766
+ if (!contains(seen, computed)) {
1767
+ seen.push(computed);
1768
+ result.push(value);
1769
+ }
1770
+ } else if (!contains(result, value)) {
1771
+ result.push(value);
1772
+ }
1773
+ }
1774
+ return result;
1775
+ }
1776
+
1777
+ // Produce an array that contains the union: each distinct element from all of
1778
+ // the passed-in arrays.
1779
+ var union = restArguments(function(arrays) {
1780
+ return uniq(flatten$1(arrays, true, true));
1781
+ });
1782
+
1783
+ // Produce an array that contains every item shared between all the
1784
+ // passed-in arrays.
1785
+ function intersection(array) {
1786
+ var result = [];
1787
+ var argsLength = arguments.length;
1788
+ for (var i = 0, length = getLength(array); i < length; i++) {
1789
+ var item = array[i];
1790
+ if (contains(result, item)) continue;
1791
+ var j;
1792
+ for (j = 1; j < argsLength; j++) {
1793
+ if (!contains(arguments[j], item)) break;
1794
+ }
1795
+ if (j === argsLength) result.push(item);
1796
+ }
1797
+ return result;
1798
+ }
1799
+
1800
+ // Complement of zip. Unzip accepts an array of arrays and groups
1801
+ // each array's elements on shared indices.
1802
+ function unzip(array) {
1803
+ var length = (array && max(array, getLength).length) || 0;
1804
+ var result = Array(length);
1805
+
1806
+ for (var index = 0; index < length; index++) {
1807
+ result[index] = pluck$1(array, index);
1808
+ }
1809
+ return result;
1810
+ }
1811
+
1812
+ // Zip together multiple lists into a single array -- elements that share
1813
+ // an index go together.
1814
+ var zip = restArguments(unzip);
1815
+
1816
+ // Converts lists into objects. Pass either a single array of `[key, value]`
1817
+ // pairs, or two parallel arrays of the same length -- one of keys, and one of
1818
+ // the corresponding values. Passing by pairs is the reverse of `_.pairs`.
1819
+ function object(list, values) {
1820
+ var result = {};
1821
+ for (var i = 0, length = getLength(list); i < length; i++) {
1822
+ if (values) {
1823
+ result[list[i]] = values[i];
1824
+ } else {
1825
+ result[list[i][0]] = list[i][1];
1826
+ }
1827
+ }
1828
+ return result;
1829
+ }
1830
+
1831
+ // Generate an integer Array containing an arithmetic progression. A port of
1832
+ // the native Python `range()` function. See
1833
+ // [the Python documentation](https://docs.python.org/library/functions.html#range).
1834
+ function range(start, stop, step) {
1835
+ if (stop == null) {
1836
+ stop = start || 0;
1837
+ start = 0;
1838
+ }
1839
+ if (!step) {
1840
+ step = stop < start ? -1 : 1;
1841
+ }
1842
+
1843
+ var length = Math.max(Math.ceil((stop - start) / step), 0);
1844
+ var range = Array(length);
1845
+
1846
+ for (var idx = 0; idx < length; idx++, start += step) {
1847
+ range[idx] = start;
1848
+ }
1849
+
1850
+ return range;
1851
+ }
1852
+
1853
+ // Chunk a single array into multiple arrays, each containing `count` or fewer
1854
+ // items.
1855
+ function chunk(array, count) {
1856
+ if (count == null || count < 1) return [];
1857
+ var result = [];
1858
+ var i = 0, length = array.length;
1859
+ while (i < length) {
1860
+ result.push(slice.call(array, i, i += count));
1861
+ }
1862
+ return result;
1863
+ }
1864
+
1865
+ // Helper function to continue chaining intermediate results.
1866
+ function chainResult(instance, obj) {
1867
+ return instance._chain ? _$1(obj).chain() : obj;
1868
+ }
1869
+
1870
+ // Add your own custom functions to the Underscore object.
1871
+ function mixin(obj) {
1872
+ each(functions(obj), function(name) {
1873
+ var func = _$1[name] = obj[name];
1874
+ _$1.prototype[name] = function() {
1875
+ var args = [this._wrapped];
1876
+ push.apply(args, arguments);
1877
+ return chainResult(this, func.apply(_$1, args));
1878
+ };
1879
+ });
1880
+ return _$1;
1881
+ }
1882
+
1883
+ // Add all mutator `Array` functions to the wrapper.
1884
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
1885
+ var method = ArrayProto[name];
1886
+ _$1.prototype[name] = function() {
1887
+ var obj = this._wrapped;
1888
+ if (obj != null) {
1889
+ method.apply(obj, arguments);
1890
+ if ((name === 'shift' || name === 'splice') && obj.length === 0) {
1891
+ delete obj[0];
1892
+ }
1893
+ }
1894
+ return chainResult(this, obj);
1895
+ };
1896
+ });
1897
+
1898
+ // Add all accessor `Array` functions to the wrapper.
1899
+ each(['concat', 'join', 'slice'], function(name) {
1900
+ var method = ArrayProto[name];
1901
+ _$1.prototype[name] = function() {
1902
+ var obj = this._wrapped;
1903
+ if (obj != null) obj = method.apply(obj, arguments);
1904
+ return chainResult(this, obj);
1905
+ };
1906
+ });
1907
+
1908
+ // Named Exports
1909
+
1910
+ var allExports = /*#__PURE__*/Object.freeze({
1911
+ __proto__: null,
1912
+ VERSION: VERSION,
1913
+ restArguments: restArguments,
1914
+ isObject: isObject,
1915
+ isNull: isNull,
1916
+ isUndefined: isUndefined,
1917
+ isBoolean: isBoolean,
1918
+ isElement: isElement,
1919
+ isString: isString,
1920
+ isNumber: isNumber,
1921
+ isDate: isDate,
1922
+ isRegExp: isRegExp,
1923
+ isError: isError,
1924
+ isSymbol: isSymbol,
1925
+ isArrayBuffer: isArrayBuffer,
1926
+ isDataView: isDataView$1,
1927
+ isArray: isArray,
1928
+ isFunction: isFunction$1,
1929
+ isArguments: isArguments$1,
1930
+ isFinite: isFinite$1,
1931
+ isNaN: isNaN$1,
1932
+ isTypedArray: isTypedArray$1,
1933
+ isEmpty: isEmpty,
1934
+ isMatch: isMatch,
1935
+ isEqual: isEqual,
1936
+ isMap: isMap,
1937
+ isWeakMap: isWeakMap,
1938
+ isSet: isSet,
1939
+ isWeakSet: isWeakSet,
1940
+ keys: keys,
1941
+ allKeys: allKeys,
1942
+ values: values,
1943
+ pairs: pairs,
1944
+ invert: invert,
1945
+ functions: functions,
1946
+ methods: functions,
1947
+ extend: extend,
1948
+ extendOwn: extendOwn,
1949
+ assign: extendOwn,
1950
+ defaults: defaults,
1951
+ create: create,
1952
+ clone: clone,
1953
+ tap: tap,
1954
+ get: get,
1955
+ has: has,
1956
+ mapObject: mapObject$1,
1957
+ identity: identity,
1958
+ constant: constant,
1959
+ noop: noop,
1960
+ toPath: toPath$1,
1961
+ property: property,
1962
+ propertyOf: propertyOf,
1963
+ matcher: matcher,
1964
+ matches: matcher,
1965
+ times: times,
1966
+ random: random,
1967
+ now: now,
1968
+ escape: escape,
1969
+ unescape: unescape,
1970
+ templateSettings: templateSettings,
1971
+ template: template,
1972
+ result: result,
1973
+ uniqueId: uniqueId,
1974
+ chain: chain,
1975
+ iteratee: iteratee,
1976
+ partial: partial,
1977
+ bind: bind,
1978
+ bindAll: bindAll,
1979
+ memoize: memoize,
1980
+ delay: delay,
1981
+ defer: defer,
1982
+ throttle: throttle,
1983
+ debounce: debounce,
1984
+ wrap: wrap,
1985
+ negate: negate,
1986
+ compose: compose,
1987
+ after: after,
1988
+ before: before,
1989
+ once: once,
1990
+ findKey: findKey,
1991
+ findIndex: findIndex,
1992
+ findLastIndex: findLastIndex,
1993
+ sortedIndex: sortedIndex,
1994
+ indexOf: indexOf,
1995
+ lastIndexOf: lastIndexOf,
1996
+ find: find,
1997
+ detect: find,
1998
+ findWhere: findWhere,
1999
+ each: each,
2000
+ forEach: each,
2001
+ map: map,
2002
+ collect: map,
2003
+ reduce: reduce,
2004
+ foldl: reduce,
2005
+ inject: reduce,
2006
+ reduceRight: reduceRight,
2007
+ foldr: reduceRight,
2008
+ filter: filter,
2009
+ select: filter,
2010
+ reject: reject,
2011
+ every: every,
2012
+ all: every,
2013
+ some: some,
2014
+ any: some,
2015
+ contains: contains,
2016
+ includes: contains,
2017
+ include: contains,
2018
+ invoke: invoke,
2019
+ pluck: pluck$1,
2020
+ where: where,
2021
+ max: max,
2022
+ min: min,
2023
+ shuffle: shuffle,
2024
+ sample: sample,
2025
+ sortBy: sortBy,
2026
+ groupBy: groupBy,
2027
+ indexBy: indexBy,
2028
+ countBy: countBy,
2029
+ partition: partition,
2030
+ toArray: toArray,
2031
+ size: size,
2032
+ pick: pick,
2033
+ omit: omit,
2034
+ first: first,
2035
+ head: first,
2036
+ take: first,
2037
+ initial: initial,
2038
+ last: last,
2039
+ rest: rest,
2040
+ tail: rest,
2041
+ drop: rest,
2042
+ compact: compact,
2043
+ flatten: flatten,
2044
+ without: without,
2045
+ uniq: uniq,
2046
+ unique: uniq,
2047
+ union: union,
2048
+ intersection: intersection,
2049
+ difference: difference,
2050
+ unzip: unzip,
2051
+ transpose: unzip,
2052
+ zip: zip,
2053
+ object: object,
2054
+ range: range,
2055
+ chunk: chunk,
2056
+ mixin: mixin,
2057
+ 'default': _$1
2058
+ });
2059
+
2060
+ // Default Export
2061
+
2062
+ // Add all of the Underscore functions to the wrapper object.
2063
+ var _ = mixin(allExports);
2064
+ // Legacy Node.js API.
2065
+ _._ = _;
2066
+
2067
+ function getMatrixSize(matrix) {
2068
+ const matrixSize = [1, 1];
2069
+
2070
+ // We need to find the widest row and tallest column to get the correct
2071
+ // matrix size.
2072
+ _(matrix).each((matrixRow, row) => {
2073
+ let rowWidth = 0;
2074
+ _(matrixRow).each((matrixCol, col) => {
2075
+ if (matrixCol != null && matrixCol.toString().length) {
2076
+ rowWidth = col + 1;
2077
+ }
2078
+ });
2079
+
2080
+ // Matrix width:
2081
+ matrixSize[1] = Math.max(matrixSize[1], rowWidth);
2082
+
2083
+ // Matrix height:
2084
+ if (rowWidth > 0) {
2085
+ matrixSize[0] = Math.max(matrixSize[0], row + 1);
2086
+ }
2087
+ });
2088
+ return matrixSize;
2089
+ }
2090
+
2091
+ /**
2092
+ * Get the character used for separating decimals.
2093
+ */
2094
+ const getDecimalSeparator = locale => {
2095
+ var _match$;
2096
+ switch (locale) {
2097
+ // TODO(somewhatabstract): Remove this when Chrome supports the `ka`
2098
+ // locale properly.
2099
+ // https://github.com/formatjs/formatjs/issues/1526#issuecomment-559891201
2100
+ //
2101
+ // Supported locales in Chrome:
2102
+ // https://source.chromium.org/chromium/chromium/src/+/master:third_party/icu/scripts/chrome_ui_languages.list
2103
+ case "ka":
2104
+ return ",";
2105
+ default:
2106
+ const numberWithDecimalSeparator = 1.1;
2107
+ // TODO(FEI-3647): Update to use .formatToParts() once we no longer have to
2108
+ // support Safari 12.
2109
+ const match = new Intl.NumberFormat(locale).format(numberWithDecimalSeparator)
2110
+ // 0x661 is ARABIC-INDIC DIGIT ONE
2111
+ // 0x6F1 is EXTENDED ARABIC-INDIC DIGIT ONE
2112
+ .match(/[^\d\u0661\u06F1]/);
2113
+ return (_match$ = match == null ? void 0 : match[0]) != null ? _match$ : ".";
2114
+ }
2115
+ };
2116
+
2117
+ /**
2118
+ * APPROXIMATE equality on numbers and primitives.
2119
+ */
2120
+ function approximateEqual(x, y) {
2121
+ if (typeof x === "number" && typeof y === "number") {
2122
+ return Math.abs(x - y) < 1e-9;
2123
+ }
2124
+ return x === y;
2125
+ }
2126
+
2127
+ /**
2128
+ * Deep APPROXIMATE equality on primitives, numbers, arrays, and objects.
2129
+ * Recursive.
2130
+ */
2131
+ function approximateDeepEqual(x, y) {
2132
+ if (Array.isArray(x) && Array.isArray(y)) {
2133
+ if (x.length !== y.length) {
2134
+ return false;
2135
+ }
2136
+ for (let i = 0; i < x.length; i++) {
2137
+ if (!approximateDeepEqual(x[i], y[i])) {
2138
+ return false;
2139
+ }
2140
+ }
2141
+ return true;
2142
+ }
2143
+ if (Array.isArray(x) || Array.isArray(y)) {
2144
+ return false;
2145
+ }
2146
+ if (typeof x === "function" && typeof y === "function") {
2147
+ return approximateEqual(x, y);
2148
+ }
2149
+ if (typeof x === "function" || typeof y === "function") {
2150
+ return false;
2151
+ }
2152
+ if (typeof x === "object" && typeof y === "object" && !!x && !!y) {
2153
+ return x === y || _.all(x, function (v, k) {
2154
+ // @ts-expect-error - TS2536 - Type 'CollectionKey<T>' cannot be used to index type 'T'.
2155
+ return approximateDeepEqual(y[k], v);
2156
+ }) && _.all(y, function (v, k) {
2157
+ // @ts-expect-error - TS2536 - Type 'CollectionKey<T>' cannot be used to index type 'T'.
2158
+ return approximateDeepEqual(x[k], v);
2159
+ });
2160
+ }
2161
+ if (typeof x === "object" && !!x || typeof y === "object" && !!y) {
2162
+ return false;
2163
+ }
2164
+ return approximateEqual(x, y);
2165
+ }
2166
+
2167
+ // TODO(benchristel): in the future, we may want to make deepClone work for
2168
+ // Record<string, Cloneable> as well. Currently, it only does arrays.
2169
+
2170
+ function deepClone(obj) {
2171
+ if (Array.isArray(obj)) {
2172
+ return obj.map(deepClone);
2173
+ }
2174
+ return obj;
2175
+ }
2176
+
2177
+ const MOVABLES = {
2178
+ PLOT: "PLOT",
2179
+ PARABOLA: "PARABOLA",
2180
+ SINUSOID: "SINUSOID"
2181
+ };
2182
+
2183
+ // TODO(charlie): These really need to go into a utility file as they're being
2184
+ // used by both interactive-graph and now grapher.
2185
+ function canonicalSineCoefficients(coeffs) {
2186
+ // For a curve of the form f(x) = a * Sin(b * x - c) + d,
2187
+ // this function ensures that a, b > 0, and c is its
2188
+ // smallest possible positive value.
2189
+ let amplitude = coeffs[0];
2190
+ let angularFrequency = coeffs[1];
2191
+ let phase = coeffs[2];
2192
+ const verticalOffset = coeffs[3];
2193
+
2194
+ // Guarantee a > 0
2195
+ if (amplitude < 0) {
2196
+ amplitude *= -1;
2197
+ angularFrequency *= -1;
2198
+ phase *= -1;
2199
+ }
2200
+ const period = 2 * Math.PI;
2201
+ // Guarantee b > 0
2202
+ if (angularFrequency < 0) {
2203
+ angularFrequency *= -1;
2204
+ phase *= -1;
2205
+ phase += period / 2;
2206
+ }
2207
+
2208
+ // Guarantee c is smallest possible positive value
2209
+ while (phase > 0) {
2210
+ phase -= period;
2211
+ }
2212
+ while (phase < 0) {
2213
+ phase += period;
2214
+ }
2215
+ return [amplitude, angularFrequency, phase, verticalOffset];
2216
+ }
2217
+ function canonicalTangentCoefficients(coeffs) {
2218
+ // For a curve of the form f(x) = a * Tan(b * x - c) + d,
2219
+ // this function ensures that a, b > 0, and c is its
2220
+ // smallest possible positive value.
2221
+ let amplitude = coeffs[0];
2222
+ let angularFrequency = coeffs[1];
2223
+ let phase = coeffs[2];
2224
+ const verticalOffset = coeffs[3];
2225
+
2226
+ // Guarantee a > 0
2227
+ if (amplitude < 0) {
2228
+ amplitude *= -1;
2229
+ angularFrequency *= -1;
2230
+ phase *= -1;
2231
+ }
2232
+ const period = Math.PI;
2233
+ // Guarantee b > 0
2234
+ if (angularFrequency < 0) {
2235
+ angularFrequency *= -1;
2236
+ phase *= -1;
2237
+ phase += period / 2;
2238
+ }
2239
+
2240
+ // Guarantee c is smallest possible positive value
2241
+ while (phase > 0) {
2242
+ phase -= period;
2243
+ }
2244
+ while (phase < 0) {
2245
+ phase += period;
2246
+ }
2247
+ return [amplitude, angularFrequency, phase, verticalOffset];
2248
+ }
2249
+ const PlotDefaults = {
2250
+ areEqual: function (coeffs1, coeffs2) {
2251
+ return approximateDeepEqual(coeffs1, coeffs2);
2252
+ },
2253
+ movable: MOVABLES.PLOT,
2254
+ getPropsForCoeffs: function (coeffs) {
2255
+ return {
2256
+ // @ts-expect-error - TS2339 - Property 'getFunctionForCoeffs' does not exist on type '{ readonly areEqual: (coeffs1: any, coeffs2: any) => boolean; readonly Movable: any; readonly getPropsForCoeffs: (coeffs: any) => any; }'.
2257
+ fn: _.partial(this.getFunctionForCoeffs, coeffs)
2258
+ };
2259
+ }
2260
+ };
2261
+ const Linear = _.extend({}, PlotDefaults, {
2262
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/67aaf581e6d9ef9038c10558a1f70ac21c11c9f8.png",
2263
+ defaultCoords: [[0.25, 0.75], [0.75, 0.75]],
2264
+ getCoefficients: function (coords) {
2265
+ const p1 = coords[0];
2266
+ const p2 = coords[1];
2267
+ const denom = p2[0] - p1[0];
2268
+ const num = p2[1] - p1[1];
2269
+ if (denom === 0) {
2270
+ return;
2271
+ }
2272
+ const m = num / denom;
2273
+ const b = p2[1] - m * p2[0];
2274
+ return [m, b];
2275
+ },
2276
+ getFunctionForCoeffs: function (coeffs, x) {
2277
+ const m = coeffs[0];
2278
+ const b = coeffs[1];
2279
+ return m * x + b;
2280
+ },
2281
+ getEquationString: function (coords) {
2282
+ const coeffs = this.getCoefficients(coords);
2283
+ const m = coeffs[0];
2284
+ const b = coeffs[1];
2285
+ return "y = " + m.toFixed(3) + "x + " + b.toFixed(3);
2286
+ }
2287
+ });
2288
+ const Quadratic = _.extend({}, PlotDefaults, {
2289
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/e23d36e6fc29ee37174e92c9daba2a66677128ab.png",
2290
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2291
+ movable: MOVABLES.PARABOLA,
2292
+ getCoefficients: function (coords) {
2293
+ const p1 = coords[0];
2294
+ const p2 = coords[1];
2295
+
2296
+ // Parabola with vertex (h, k) has form: y = a * (h - k)^2 + k
2297
+ const h = p1[0];
2298
+ const k = p1[1];
2299
+
2300
+ // Use these to calculate familiar a, b, c
2301
+ const a = (p2[1] - k) / ((p2[0] - h) * (p2[0] - h));
2302
+ const b = -2 * h * a;
2303
+ const c = a * h * h + k;
2304
+ return [a, b, c];
2305
+ },
2306
+ getFunctionForCoeffs: function (coeffs, x) {
2307
+ const a = coeffs[0];
2308
+ const b = coeffs[1];
2309
+ const c = coeffs[2];
2310
+ return (a * x + b) * x + c;
2311
+ },
2312
+ getPropsForCoeffs: function (coeffs) {
2313
+ return {
2314
+ a: coeffs[0],
2315
+ b: coeffs[1],
2316
+ c: coeffs[2]
2317
+ };
2318
+ },
2319
+ getEquationString: function (coords) {
2320
+ const coeffs = this.getCoefficients(coords);
2321
+ const a = coeffs[0];
2322
+ const b = coeffs[1];
2323
+ const c = coeffs[2];
2324
+ return "y = " + a.toFixed(3) + "x^2 + " + b.toFixed(3) + "x + " + c.toFixed(3);
2325
+ }
2326
+ });
2327
+ const Sinusoid = _.extend({}, PlotDefaults, {
2328
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/3d68e7718498475f53b206c2ab285626baf8857e.png",
2329
+ defaultCoords: [[0.5, 0.5], [0.6, 0.6]],
2330
+ movable: MOVABLES.SINUSOID,
2331
+ getCoefficients: function (coords) {
2332
+ const p1 = coords[0];
2333
+ const p2 = coords[1];
2334
+ const a = p2[1] - p1[1];
2335
+ const b = Math.PI / (2 * (p2[0] - p1[0]));
2336
+ const c = p1[0] * b;
2337
+ const d = p1[1];
2338
+ return [a, b, c, d];
2339
+ },
2340
+ getFunctionForCoeffs: function (coeffs, x) {
2341
+ const a = coeffs[0];
2342
+ const b = coeffs[1];
2343
+ const c = coeffs[2];
2344
+ const d = coeffs[3];
2345
+ return a * Math.sin(b * x - c) + d;
2346
+ },
2347
+ getPropsForCoeffs: function (coeffs) {
2348
+ return {
2349
+ a: coeffs[0],
2350
+ b: coeffs[1],
2351
+ c: coeffs[2],
2352
+ d: coeffs[3]
2353
+ };
2354
+ },
2355
+ getEquationString: function (coords) {
2356
+ const coeffs = this.getCoefficients(coords);
2357
+ const a = coeffs[0];
2358
+ const b = coeffs[1];
2359
+ const c = coeffs[2];
2360
+ const d = coeffs[3];
2361
+ return "y = " + a.toFixed(3) + " sin(" + b.toFixed(3) + "x - " + c.toFixed(3) + ") + " + d.toFixed(3);
2362
+ },
2363
+ areEqual: function (coeffs1, coeffs2) {
2364
+ return approximateDeepEqual(canonicalSineCoefficients(coeffs1), canonicalSineCoefficients(coeffs2));
2365
+ }
2366
+ });
2367
+ const Tangent = _.extend({}, PlotDefaults, {
2368
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/7db80d23c35214f98659fe1cf0765811c1bbfbba.png",
2369
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2370
+ getCoefficients: function (coords) {
2371
+ const p1 = coords[0];
2372
+ const p2 = coords[1];
2373
+ const a = p2[1] - p1[1];
2374
+ const b = Math.PI / (4 * (p2[0] - p1[0]));
2375
+ const c = p1[0] * b;
2376
+ const d = p1[1];
2377
+ return [a, b, c, d];
2378
+ },
2379
+ getFunctionForCoeffs: function (coeffs, x) {
2380
+ const a = coeffs[0];
2381
+ const b = coeffs[1];
2382
+ const c = coeffs[2];
2383
+ const d = coeffs[3];
2384
+ return a * Math.tan(b * x - c) + d;
2385
+ },
2386
+ getEquationString: function (coords) {
2387
+ const coeffs = this.getCoefficients(coords);
2388
+ const a = coeffs[0];
2389
+ const b = coeffs[1];
2390
+ const c = coeffs[2];
2391
+ const d = coeffs[3];
2392
+ return "y = " + a.toFixed(3) + " sin(" + b.toFixed(3) + "x - " + c.toFixed(3) + ") + " + d.toFixed(3);
2393
+ },
2394
+ areEqual: function (coeffs1, coeffs2) {
2395
+ return approximateDeepEqual(canonicalTangentCoefficients(coeffs1), canonicalTangentCoefficients(coeffs2));
2396
+ }
2397
+ });
2398
+ const Exponential = _.extend({}, PlotDefaults, {
2399
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/9cbfad55525e3ce755a31a631b074670a5dad611.png",
2400
+ defaultCoords: [[0.5, 0.55], [0.75, 0.75]],
2401
+ defaultAsymptote: [[0, 0.5], [1.0, 0.5]],
2402
+ /**
2403
+ * Add extra constraints for movement of the points or asymptote (below):
2404
+ * newCoord: [x, y]
2405
+ * The end position of the point or asymptote endpoint
2406
+ * oldCoord: [x, y]
2407
+ * The old position of the point or asymptote endpoint
2408
+ * coords:
2409
+ * An array of coordinates representing the proposed end configuration
2410
+ * of the plot coordinates.
2411
+ * asymptote:
2412
+ * An array of coordinates representing the proposed end configuration
2413
+ * of the asymptote.
2414
+ *
2415
+ * Return: either a coordinate (to be used as the resulting coordinate of
2416
+ * the move) or a boolean, where `true` uses newCoord as the resulting
2417
+ * coordinate, and `false` uses oldCoord as the resulting coordinate.
2418
+ */
2419
+ extraCoordConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2420
+ const y = asymptote[0][1];
2421
+ return _.all(coords, coord => coord[1] !== y);
2422
+ },
2423
+ extraAsymptoteConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2424
+ const y = newCoord[1];
2425
+ const isValid = _.all(coords, coord => coord[1] > y) || _.all(coords, coord => coord[1] < y);
2426
+ if (isValid) {
2427
+ return [oldCoord[0], y];
2428
+ }
2429
+ // Snap the asymptote as close as possible, i.e., if the user moves
2430
+ // the mouse really quickly into an invalid region
2431
+ const oldY = oldCoord[1];
2432
+ const wasBelow = _.all(coords, coord => coord[1] > oldY);
2433
+ if (wasBelow) {
2434
+ const bottomMost = _.min(_.map(coords, coord => coord[1]));
2435
+ return [oldCoord[0], bottomMost - graph.snapStep[1]];
2436
+ }
2437
+ const topMost = _.max(_.map(coords, coord => coord[1]));
2438
+ return [oldCoord[0], topMost + graph.snapStep[1]];
2439
+ },
2440
+ allowReflectOverAsymptote: true,
2441
+ getCoefficients: function (coords, asymptote) {
2442
+ const p1 = coords[0];
2443
+ const p2 = coords[1];
2444
+ const c = asymptote[0][1];
2445
+ const b = Math.log((p1[1] - c) / (p2[1] - c)) / (p1[0] - p2[0]);
2446
+ const a = (p1[1] - c) / Math.exp(b * p1[0]);
2447
+ return [a, b, c];
2448
+ },
2449
+ getFunctionForCoeffs: function (coeffs, x) {
2450
+ const a = coeffs[0];
2451
+ const b = coeffs[1];
2452
+ const c = coeffs[2];
2453
+ return a * Math.exp(b * x) + c;
2454
+ },
2455
+ getEquationString: function (coords, asymptote) {
2456
+ if (!asymptote) {
2457
+ return null;
2458
+ }
2459
+ const coeffs = this.getCoefficients(coords, asymptote);
2460
+ const a = coeffs[0];
2461
+ const b = coeffs[1];
2462
+ const c = coeffs[2];
2463
+ return "y = " + a.toFixed(3) + "e^(" + b.toFixed(3) + "x) + " + c.toFixed(3);
2464
+ }
2465
+ });
2466
+ const Logarithm = _.extend({}, PlotDefaults, {
2467
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/f6491e99d34af34d924bfe0231728ad912068dc3.png",
2468
+ defaultCoords: [[0.55, 0.5], [0.75, 0.75]],
2469
+ defaultAsymptote: [[0.5, 0], [0.5, 1.0]],
2470
+ extraCoordConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2471
+ const x = asymptote[0][0];
2472
+ return _.all(coords, coord => coord[0] !== x) && coords[0][1] !== coords[1][1];
2473
+ },
2474
+ extraAsymptoteConstraint: function (newCoord, oldCoord, coords, asymptote, graph) {
2475
+ const x = newCoord[0];
2476
+ const isValid = _.all(coords, coord => coord[0] > x) || _.all(coords, coord => coord[0] < x);
2477
+ if (isValid) {
2478
+ return [x, oldCoord[1]];
2479
+ }
2480
+ // Snap the asymptote as close as possible, i.e., if the user moves
2481
+ // the mouse really quickly into an invalid region
2482
+ const oldX = oldCoord[0];
2483
+ const wasLeft = _.all(coords, coord => coord[0] > oldX);
2484
+ if (wasLeft) {
2485
+ const leftMost = _.min(_.map(coords, coord => coord[0]));
2486
+ return [leftMost - graph.snapStep[0], oldCoord[1]];
2487
+ }
2488
+ const rightMost = _.max(_.map(coords, coord => coord[0]));
2489
+ return [rightMost + graph.snapStep[0], oldCoord[1]];
2490
+ },
2491
+ allowReflectOverAsymptote: true,
2492
+ getCoefficients: function (coords, asymptote) {
2493
+ // It's easiest to calculate the logarithm's coefficients by thinking
2494
+ // about it as the inverse of the exponential, so we flip x and y and
2495
+ // perform some algebra on the coefficients. This also unifies the
2496
+ // logic between the two 'models'.
2497
+ const flip = coord => [coord[1], coord[0]];
2498
+ const inverseCoeffs = Exponential.getCoefficients(_.map(coords, flip), _.map(asymptote, flip));
2499
+ if (inverseCoeffs) {
2500
+ const c = -inverseCoeffs[2] / inverseCoeffs[0];
2501
+ const b = 1 / inverseCoeffs[0];
2502
+ const a = 1 / inverseCoeffs[1];
2503
+ return [a, b, c];
2504
+ }
2505
+ },
2506
+ getFunctionForCoeffs: function (coeffs, x, asymptote) {
2507
+ const a = coeffs[0];
2508
+ const b = coeffs[1];
2509
+ const c = coeffs[2];
2510
+ return a * Math.log(b * x + c);
2511
+ },
2512
+ getEquationString: function (coords, asymptote) {
2513
+ if (!asymptote) {
2514
+ return null;
2515
+ }
2516
+ const coeffs = this.getCoefficients(coords, asymptote);
2517
+ const a = coeffs[0];
2518
+ const b = coeffs[1];
2519
+ const c = coeffs[2];
2520
+ return "y = ln(" + a.toFixed(3) + "x + " + b.toFixed(3) + ") + " + c.toFixed(3);
2521
+ }
2522
+ });
2523
+ const AbsoluteValue = _.extend({}, PlotDefaults, {
2524
+ url: "https://ka-perseus-graphie.s3.amazonaws.com/8256a630175a0cb1d11de223d6de0266daf98721.png",
2525
+ defaultCoords: [[0.5, 0.5], [0.75, 0.75]],
2526
+ getCoefficients: function (coords) {
2527
+ const p1 = coords[0];
2528
+ const p2 = coords[1];
2529
+ const denom = p2[0] - p1[0];
2530
+ const num = p2[1] - p1[1];
2531
+ if (denom === 0) {
2532
+ return;
2533
+ }
2534
+ let m = Math.abs(num / denom);
2535
+ if (p2[1] < p1[1]) {
2536
+ m *= -1;
2537
+ }
2538
+ const horizontalOffset = p1[0];
2539
+ const verticalOffset = p1[1];
2540
+ return [m, horizontalOffset, verticalOffset];
2541
+ },
2542
+ getFunctionForCoeffs: function (coeffs, x) {
2543
+ const m = coeffs[0];
2544
+ const horizontalOffset = coeffs[1];
2545
+ const verticalOffset = coeffs[2];
2546
+ return m * Math.abs(x - horizontalOffset) + verticalOffset;
2547
+ },
2548
+ getEquationString: function (coords) {
2549
+ const coeffs = this.getCoefficients(coords);
2550
+ const m = coeffs[0];
2551
+ const horizontalOffset = coeffs[1];
2552
+ const verticalOffset = coeffs[2];
2553
+ return "y = " + m.toFixed(3) + "| x - " + horizontalOffset.toFixed(3) + "| + " + verticalOffset.toFixed(3);
2554
+ }
2555
+ });
2556
+
2557
+ /* Utility functions for dealing with graphing interfaces. */
2558
+ const functionTypeMapping = {
2559
+ linear: Linear,
2560
+ quadratic: Quadratic,
2561
+ sinusoid: Sinusoid,
2562
+ tangent: Tangent,
2563
+ exponential: Exponential,
2564
+ logarithm: Logarithm,
2565
+ absolute_value: AbsoluteValue
2566
+ };
2567
+ const allTypes = _.keys(functionTypeMapping);
2568
+ function functionForType(type) {
2569
+ // @ts-expect-error: TypeScript doesn't know how to use deal with generics
2570
+ // and conditional types in this way.
2571
+ return functionTypeMapping[type];
2572
+ }
2573
+
2574
+ var grapherUtil = /*#__PURE__*/Object.freeze({
2575
+ __proto__: null,
2576
+ MOVABLES: MOVABLES,
2577
+ allTypes: allTypes,
2578
+ functionForType: functionForType
2579
+ });
2580
+
43
2581
  // This file is processed by a Rollup plugin (replace) to inject the production
44
2582
  const libName = "@khanacademy/perseus-core";
45
- const libVersion = "3.0.5";
2583
+ const libVersion = "3.2.0";
46
2584
  addLibraryVersionToPerseusDebug(libName, libVersion);
47
2585
 
48
2586
  /**
@@ -97,5 +2635,284 @@ class PerseusError extends Error {
97
2635
  }
98
2636
  }
99
2637
 
100
- export { Errors, PerseusError, addLibraryVersionToPerseusDebug, libVersion };
2638
+ /**
2639
+ * The Perseus "data schema" file.
2640
+ *
2641
+ * This file, and the types in it, represents the "data schema" that Perseus
2642
+ * uses. The @khanacademy/perseus-editor package edits and produces objects
2643
+ * that conform to the types in this file. Similarly, the top-level renderers
2644
+ * in @khanacademy/perseus, consume objects that conform to these types.
2645
+ *
2646
+ * WARNING: This file should not import any types from elsewhere so that it is
2647
+ * easy to reason about changes that alter the Perseus schema. This helps
2648
+ * ensure that it is not changed accidentally when upgrading a dependant
2649
+ * package or other part of Perseus code. Note that TypeScript does type
2650
+ * checking via something called "structural typing". This means that as long
2651
+ * as the shape of a type matches, the name it goes by doesn't matter. As a
2652
+ * result, a `Coord` type that looks like this `[x: number, y: number]` is
2653
+ * _identical_, in TypeScript's eyes, to this `Vector2` type `[x: number, y:
2654
+ * number]`. Also, with tuples, the labels for each entry is ignored, so `[x:
2655
+ * number, y: number]` is compatible with `[min: number, max: number]`. The
2656
+ * labels are for humans, not TypeScript. :)
2657
+ *
2658
+ * If you make changes to types in this file, be very sure that:
2659
+ *
2660
+ * a) the changes are backwards compatible. If they are not, old data from
2661
+ * previous versions of the "schema" could become unrenderable, or worse,
2662
+ * introduce hard-to-diagnose bugs.
2663
+ * b) the parsing code (`util/parse-perseus-json/`) is updated to handle
2664
+ * the new format _as well as_ the old format.
2665
+ */
2666
+
2667
+ // TODO(FEI-4010): Remove `Perseus` prefix for all types here
2668
+
2669
+ // Same name as Mafs
2670
+
2671
+ /**
2672
+ * Our core set of Perseus widgets.
2673
+ *
2674
+ * This interface is the basis for "registering" all Perseus widget types.
2675
+ * There should be one key/value pair for each supported widget. If you create
2676
+ * a new widget, an entry should be added to this interface. Note that this
2677
+ * only registers the widget options type, you'll also need to register the
2678
+ * widget so that it's available at runtime (@see
2679
+ * {@link file://./widgets.ts#registerWidget}).
2680
+ *
2681
+ * Importantly, the key should be the name that is used in widget IDs. For most
2682
+ * widgets that is the same as the widget option's `type` field. In cases where
2683
+ * a widget has been deprecated and replaced with the deprecated-standin
2684
+ * widget, it should be the original widget type!
2685
+ *
2686
+ * If you define the widget outside of this package, you can still add the new
2687
+ * widget to this interface by writing the following in that package that
2688
+ * contains the widget. TypeScript will merge that definition of the
2689
+ * `PerseusWidgets` with the one defined below.
2690
+ *
2691
+ * ```typescript
2692
+ * declare module "@khanacademy/perseus" {
2693
+ * interface PerseusWidgetTypes {
2694
+ * // A new widget
2695
+ * "new-awesomeness": MyAwesomeNewWidget;
2696
+ *
2697
+ * // A deprecated widget
2698
+ * "super-old-widget": DeprecatedStandinWidget;
2699
+ * }
2700
+ * }
2701
+ *
2702
+ * // The new widget's options definition
2703
+ * type MyAwesomeNewWidget = WidgetOptions<'new-awesomeness', MyAwesomeNewWidgetOptions>;
2704
+ *
2705
+ * // The deprecated widget's options definition
2706
+ * type SuperOldWidget = WidgetOptions<'super-old-widget', object>;
2707
+ * ```
2708
+ *
2709
+ * This interface can be extended through the magic of TypeScript "Declaration
2710
+ * merging". Specifically, we augment this module and extend this interface.
2711
+ *
2712
+ * @see {@link https://www.typescriptlang.org/docs/handbook/declaration-merging.html#module-augmentation}
2713
+ */
2714
+
2715
+ /**
2716
+ * A map of widget IDs to widget options. This is most often used as the type
2717
+ * for a set of widgets defined in a `PerseusItem` but can also be useful to
2718
+ * represent a function parameter where only `widgets` from a `PerseusItem` are
2719
+ * needed. Today Widget IDs are made up of the widget type and an incrementing
2720
+ * integer (eg. `interactive-graph 1` or `radio 3`). It is suggested to avoid
2721
+ * reading/parsing the widget id to derive any information from it, except in
2722
+ * the case of this map.
2723
+ *
2724
+ * @see {@link PerseusWidgetTypes} additional widgets can be added to this map type
2725
+ * by augmenting the PerseusWidgetTypes with new widget types!
2726
+ */
2727
+
2728
+ /**
2729
+ * A "PerseusItem" is a classic Perseus item. It is rendered by the
2730
+ * `ServerItemRenderer` and the layout is pre-set.
2731
+ *
2732
+ * To render more complex Perseus items, see the `Item` type in the multi item
2733
+ * area.
2734
+ */
2735
+
2736
+ /**
2737
+ * A "PerseusArticle" is an item that is meant to be rendered as an article.
2738
+ * This item is never scored and is rendered by the `ArticleRenderer`.
2739
+ */
2740
+
2741
+ const ItemExtras = [
2742
+ // The user might benefit from using a Scientific Calculator. Provided on Khan Academy when true
2743
+ "calculator",
2744
+ // The user might benefit from using a statistics Chi Squared Table like https://people.richland.edu/james/lecture/m170/tbl-chi.html
2745
+ "chi2Table",
2746
+ // The user might benefit from a monthly payments calculator. Provided on Khan Academy when true
2747
+ "financialCalculatorMonthlyPayment",
2748
+ // The user might benefit from a total amount calculator. Provided on Khan Academy when true
2749
+ "financialCalculatorTotalAmount",
2750
+ // The user might benefit from a time to pay off calculator. Provided on Khan Academy when true
2751
+ "financialCalculatorTimeToPayOff",
2752
+ // The user might benefit from using a Periodic Table of Elements. Provided on Khan Academy when true
2753
+ "periodicTable",
2754
+ // The user might benefit from using a Periodic Table of Elements with key. Provided on Khan Academy when true
2755
+ "periodicTableWithKey",
2756
+ // The user might benefit from using a statistics T Table like https://www.statisticshowto.com/tables/t-distribution-table/
2757
+ "tTable",
2758
+ // The user might benefit from using a statistics Z Table like https://www.ztable.net/
2759
+ "zTable"];
2760
+
2761
+ /**
2762
+ * The type representing the common structure of all widget's options. The
2763
+ * `Options` generic type represents the widget-specific option data.
2764
+ */
2765
+
2766
+ // prettier-ignore
2767
+
2768
+ // prettier-ignore
2769
+
2770
+ // prettier-ignore
2771
+
2772
+ // prettier-ignore
2773
+
2774
+ // prettier-ignore
2775
+
2776
+ // prettier-ignore
2777
+
2778
+ // prettier-ignore
2779
+
2780
+ // prettier-ignore
2781
+
2782
+ // prettier-ignore
2783
+
2784
+ // prettier-ignore
2785
+
2786
+ // prettier-ignore
2787
+
2788
+ // prettier-ignore
2789
+
2790
+ // prettier-ignore
2791
+
2792
+ // prettier-ignore
2793
+
2794
+ // prettier-ignore
2795
+
2796
+ // prettier-ignore
2797
+
2798
+ // prettier-ignore
2799
+
2800
+ // prettier-ignore
2801
+
2802
+ // prettier-ignore
2803
+
2804
+ // prettier-ignore
2805
+
2806
+ // prettier-ignore
2807
+
2808
+ // prettier-ignore
2809
+
2810
+ // prettier-ignore
2811
+
2812
+ // prettier-ignore
2813
+
2814
+ // prettier-ignore
2815
+
2816
+ // prettier-ignore
2817
+
2818
+ // prettier-ignore
2819
+
2820
+ // prettier-ignore
2821
+
2822
+ // prettier-ignore
2823
+
2824
+ // prettier-ignore
2825
+
2826
+ // prettier-ignore
2827
+
2828
+ // prettier-ignore
2829
+
2830
+ // prettier-ignore
2831
+
2832
+ // prettier-ignore
2833
+
2834
+ //prettier-ignore
2835
+
2836
+ /**
2837
+ * A background image applied to various widgets.
2838
+ */
2839
+
2840
+ /**
2841
+ * The type of markings to display on the graph.
2842
+ * - axes: shows the axes without the gride lines
2843
+ * - graph: shows the axes and the grid lines
2844
+ * - grid: shows only the grid lines
2845
+ * - none: shows no markings
2846
+ */
2847
+
2848
+ const PerseusExpressionAnswerFormConsidered = ["correct", "wrong", "ungraded"];
2849
+
2850
+ // 2D range: xMin, xMax, yMin, yMax
2851
+
2852
+ const lockedFigureColorNames = ["blue", "green", "grayH", "purple", "pink", "orange", "red"];
2853
+ const lockedFigureColors = {
2854
+ blue: "#3D7586",
2855
+ green: "#447A53",
2856
+ grayH: "#3B3D45",
2857
+ purple: "#594094",
2858
+ pink: "#B25071",
2859
+ red: "#D92916",
2860
+ orange: "#946700"
2861
+ };
2862
+ const lockedFigureFillStyles = {
2863
+ none: 0,
2864
+ white: 1,
2865
+ translucent: 0.4,
2866
+ solid: 1
2867
+ };
2868
+
2869
+ // Not associated with a specific figure
2870
+
2871
+ const plotterPlotTypes = ["bar", "line", "pic", "histogram", "dotplot"];
2872
+
2873
+ /**
2874
+ * _ utilities for objects
2875
+ */
2876
+
2877
+ /**
2878
+ * Does a pluck on keys inside objects in an object
2879
+ *
2880
+ * Ex:
2881
+ * tools = {
2882
+ * translation: {
2883
+ * enabled: true
2884
+ * },
2885
+ * rotation: {
2886
+ * enabled: false
2887
+ * }
2888
+ * };
2889
+ * pluckObject(tools, "enabled") returns {
2890
+ * translation: true
2891
+ * rotation: false
2892
+ * }
2893
+ */
2894
+ const pluck = function pluck(table, subKey) {
2895
+ return _.object(_.map(table, function (value, key) {
2896
+ return [key, value[subKey]];
2897
+ }));
2898
+ };
2899
+
2900
+ /**
2901
+ * Maps an object to an object
2902
+ *
2903
+ * > mapObject({a: '1', b: '2'}, (value, key) => {
2904
+ * return value + 1;
2905
+ * });
2906
+ * {a: 2, b: 3}
2907
+ */
2908
+ const mapObject = function mapObject(obj, lambda) {
2909
+ const result = {};
2910
+ Object.keys(obj).forEach(key => {
2911
+ // @ts-expect-error - TS2345 - Argument of type 'string' is not assignable to parameter of type 'K'.
2912
+ result[key] = lambda(obj[key], key);
2913
+ });
2914
+ return result;
2915
+ };
2916
+
2917
+ export { Errors, grapherUtil as GrapherUtil, ItemExtras, PerseusError, PerseusExpressionAnswerFormConsidered, addLibraryVersionToPerseusDebug, approximateDeepEqual, approximateEqual, deepClone, getDecimalSeparator, getMatrixSize, libVersion, lockedFigureColorNames, lockedFigureColors, lockedFigureFillStyles, mapObject, plotterPlotTypes, pluck };
101
2918
  //# sourceMappingURL=index.js.map