FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
mathjs/src/utils/array.js at develop · rvramesh/mathjs · GitHub
rvramesh
/
mathjs
Public
forked from
josdejong/mathjs
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
mathjs
/
src
/
utils
/
array.js
Copy path
More file actions
More file actions
Latest commit
History
History
History
614 lines (539 loc) · 15.7 KB
Breadcrumbs
mathjs
/
src
/
utils
/
array.js
Copy path
File metadata and controls
614 lines (539 loc) · 15.7 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
import
{
isInteger
}
from
'./number.js'
import
{
isNumber
}
from
'./is.js'
import
{
format
}
from
'./string.js'
import
{
DimensionError
}
from
'../error/DimensionError.js'
import
{
IndexError
}
from
'../error/IndexError.js'
/**
* Calculate the size of a multi dimensional array.
* This function checks the size of the first entry, it does not validate
* whether all dimensions match. (use function `validate` for that)
*
@param
{
Array
} x
*
@Return
{Number[]} size
*/
export
function
arraySize
(
x
)
{
const
s
=
[
]
while
(
Array
.
isArray
(
x
)
)
{
s
.
push
(
x
.
length
)
x
=
x
[
0
]
}
return
s
}
/**
* Recursively validate whether each element in a multi dimensional array
* has a size corresponding to the provided size array.
*
@param
{
Array
} array Array to be validated
*
@param
{
number[]
} size Array with the size of each dimension
*
@param
{
number
} dim Current dimension
*
@throws
DimensionError
*
@private
*/
function
_validate
(
array
,
size
,
dim
)
{
let
i
const
len
=
array
.
length
if
(
len
!==
size
[
dim
]
)
{
throw
new
DimensionError
(
len
,
size
[
dim
]
)
}
if
(
dim
<
size
.
length
-
1
)
{
// recursively validate each child array
const
dimNext
=
dim
+
1
for
(
i
=
0
;
i
<
len
;
i
++
)
{
const
child
=
array
[
i
]
if
(
!
Array
.
isArray
(
child
)
)
{
throw
new
DimensionError
(
size
.
length
-
1
,
size
.
length
,
'<'
)
}
_validate
(
array
[
i
]
,
size
,
dimNext
)
}
}
else
{
// last dimension. none of the childs may be an array
for
(
i
=
0
;
i
<
len
;
i
++
)
{
if
(
Array
.
isArray
(
array
[
i
]
)
)
{
throw
new
DimensionError
(
size
.
length
+
1
,
size
.
length
,
'>'
)
}
}
}
}
/**
* Validate whether each element in a multi dimensional array has
* a size corresponding to the provided size array.
*
@param
{
Array
} array Array to be validated
*
@param
{
number[]
} size Array with the size of each dimension
*
@throws
DimensionError
*/
export
function
validate
(
array
,
size
)
{
const
isScalar
=
(
size
.
length
===
0
)
if
(
isScalar
)
{
// scalar
if
(
Array
.
isArray
(
array
)
)
{
throw
new
DimensionError
(
array
.
length
,
0
)
}
}
else
{
// array
_validate
(
array
,
size
,
0
)
}
}
/**
* Test whether index is an integer number with index >= 0 and index < length
* when length is provided
*
@param
{
number
} index Zero-based index
*
@param
{
number
} [length] Length of the array
*/
export
function
validateIndex
(
index
,
length
)
{
if
(
!
isNumber
(
index
)
||
!
isInteger
(
index
)
)
{
throw
new
TypeError
(
'Index must be an integer (value: '
+
index
+
')'
)
}
if
(
index
<
0
||
(
typeof
length
===
'number'
&&
index
>=
length
)
)
{
throw
new
IndexError
(
index
,
length
)
}
}
/**
* Resize a multi dimensional array. The resized array is returned.
*
@param
{
Array
} array Array to be resized
*
@param
{
Array.<number>
} size Array with the size of each dimension
*
@param
{
*
} [defaultValue=0] Value to be filled in in new entries,
* zero by default. Specify for example `null`,
* to clearly see entries that are not explicitly
* set.
*
@return
{
Array
} array The resized array
*/
export
function
resize
(
array
,
size
,
defaultValue
)
{
// TODO: add support for scalars, having size=[] ?
// check the type of the arguments
if
(
!
Array
.
isArray
(
array
)
||
!
Array
.
isArray
(
size
)
)
{
throw
new
TypeError
(
'Array expected'
)
}
if
(
size
.
length
===
0
)
{
throw
new
Error
(
'Resizing to scalar is not supported'
)
}
// check whether size contains positive integers
size
.
forEach
(
function
(
value
)
{
if
(
!
isNumber
(
value
)
||
!
isInteger
(
value
)
||
value
<
0
)
{
throw
new
TypeError
(
'Invalid size, must contain positive integers '
+
'(size: '
+
format
(
size
)
+
')'
)
}
}
)
// recursively resize the array
const
_defaultValue
=
(
defaultValue
!==
undefined
)
?
defaultValue
:
0
_resize
(
array
,
size
,
0
,
_defaultValue
)
return
array
}
/**
* Recursively resize a multi dimensional array
*
@param
{
Array
} array Array to be resized
*
@param
{
number[]
} size Array with the size of each dimension
*
@param
{
number
} dim Current dimension
*
@param
{
*
} [defaultValue] Value to be filled in in new entries,
* undefined by default.
*
@private
*/
function
_resize
(
array
,
size
,
dim
,
defaultValue
)
{
let
i
let
elem
const
oldLen
=
array
.
length
const
newLen
=
size
[
dim
]
const
minLen
=
Math
.
min
(
oldLen
,
newLen
)
// apply new length
array
.
length
=
newLen
if
(
dim
<
size
.
length
-
1
)
{
// non-last dimension
const
dimNext
=
dim
+
1
// resize existing child arrays
for
(
i
=
0
;
i
<
minLen
;
i
++
)
{
// resize child array
elem
=
array
[
i
]
if
(
!
Array
.
isArray
(
elem
)
)
{
elem
=
[
elem
]
// add a dimension
array
[
i
]
=
elem
}
_resize
(
elem
,
size
,
dimNext
,
defaultValue
)
}
// create new child arrays
for
(
i
=
minLen
;
i
<
newLen
;
i
++
)
{
// get child array
elem
=
[
]
array
[
i
]
=
elem
// resize new child array
_resize
(
elem
,
size
,
dimNext
,
defaultValue
)
}
}
else
{
// last dimension
// remove dimensions of existing values
for
(
i
=
0
;
i
<
minLen
;
i
++
)
{
while
(
Array
.
isArray
(
array
[
i
]
)
)
{
array
[
i
]
=
array
[
i
]
[
0
]
}
}
// fill new elements with the default value
for
(
i
=
minLen
;
i
<
newLen
;
i
++
)
{
array
[
i
]
=
defaultValue
}
}
}
/**
* Re-shape a multi dimensional array to fit the specified dimensions
*
@param
{
Array
} array Array to be reshaped
*
@param
{
Array.<number>
} sizes List of sizes for each dimension
*
@returns
{
Array
} Array whose data has been formatted to fit the
* specified dimensions
*
*
@throws
{
DimensionError
} If the product of the new dimension sizes does
* not equal that of the old ones
*/
export
function
reshape
(
array
,
sizes
)
{
const
flatArray
=
flatten
(
array
)
const
currentLength
=
flatArray
.
length
if
(
!
Array
.
isArray
(
array
)
||
!
Array
.
isArray
(
sizes
)
)
{
throw
new
TypeError
(
'Array expected'
)
}
if
(
sizes
.
length
===
0
)
{
throw
new
DimensionError
(
0
,
currentLength
,
'!='
)
}
sizes
=
processSizesWildcard
(
sizes
,
currentLength
)
const
newLength
=
product
(
sizes
)
if
(
currentLength
!==
newLength
)
{
throw
new
DimensionError
(
newLength
,
currentLength
,
'!='
)
}
try
{
return
_reshape
(
flatArray
,
sizes
)
}
catch
(
e
)
{
if
(
e
instanceof
DimensionError
)
{
throw
new
DimensionError
(
newLength
,
currentLength
,
'!='
)
}
throw
e
}
}
/**
* Replaces the wildcard -1 in the sizes array.
*
@param
{
Array.<number>
} sizes List of sizes for each dimension. At most on wildcard.
*
@param
{
number
} currentLength Number of elements in the array.
*
@throws
{
Error
} If more than one wildcard or unable to replace it.
*
@returns
{
Array.<number>
} The sizes array with wildcard replaced.
*/
export
function
processSizesWildcard
(
sizes
,
currentLength
)
{
const
newLength
=
product
(
sizes
)
const
processedSizes
=
sizes
.
slice
(
)
const
WILDCARD
=
-
1
const
wildCardIndex
=
sizes
.
indexOf
(
WILDCARD
)
const
isMoreThanOneWildcard
=
sizes
.
indexOf
(
WILDCARD
,
wildCardIndex
+
1
)
>=
0
if
(
isMoreThanOneWildcard
)
{
throw
new
Error
(
'More than one wildcard in sizes'
)
}
const
hasWildcard
=
wildCardIndex
>=
0
const
canReplaceWildcard
=
currentLength
%
newLength
===
0
if
(
hasWildcard
)
{
if
(
canReplaceWildcard
)
{
processedSizes
[
wildCardIndex
]
=
-
currentLength
/
newLength
}
else
{
throw
new
Error
(
'Could not replace wildcard, since '
+
currentLength
+
' is no multiple of '
+
(
-
newLength
)
)
}
}
return
processedSizes
}
/**
* Computes the product of all array elements.
*
@param
{
Array<number>
} array Array of factors
*
@returns
{
number
} Product of all elements
*/
function
product
(
array
)
{
return
array
.
reduce
(
(
prev
,
curr
)
=>
prev
*
curr
,
1
)
}
/**
* Iteratively re-shape a multi dimensional array to fit the specified dimensions
*
@param
{
Array
} array Array to be reshaped
*
@param
{
Array.<number>
} sizes List of sizes for each dimension
*
@returns
{
Array
} Array whose data has been formatted to fit the
* specified dimensions
*/
function
_reshape
(
array
,
sizes
)
{
// testing if there are enough elements for the requested shape
let
tmpArray
=
array
let
tmpArray2
// for each dimensions starting by the last one and ignoring the first one
for
(
let
sizeIndex
=
sizes
.
length
-
1
;
sizeIndex
>
0
;
sizeIndex
--
)
{
const
size
=
sizes
[
sizeIndex
]
tmpArray2
=
[
]
// aggregate the elements of the current tmpArray in elements of the requested size
const
length
=
tmpArray
.
length
/
size
for
(
let
i
=
0
;
i
<
length
;
i
++
)
{
tmpArray2
.
push
(
tmpArray
.
slice
(
i
*
size
,
(
i
+
1
)
*
size
)
)
}
// set it as the new tmpArray for the next loop turn or for return
tmpArray
=
tmpArray2
}
return
tmpArray
}
/**
* Squeeze a multi dimensional array
*
@param
{
Array
} array
*
@param
{
Array
} [size]
*
@returns
{
Array
} returns the array itself
*/
export
function
squeeze
(
array
,
size
)
{
const
s
=
size
||
arraySize
(
array
)
// squeeze outer dimensions
while
(
Array
.
isArray
(
array
)
&&
array
.
length
===
1
)
{
array
=
array
[
0
]
s
.
shift
(
)
}
// find the first dimension to be squeezed
let
dims
=
s
.
length
while
(
s
[
dims
-
1
]
===
1
)
{
dims
--
}
// squeeze inner dimensions
if
(
dims
<
s
.
length
)
{
array
=
_squeeze
(
array
,
dims
,
0
)
s
.
length
=
dims
}
return
array
}
/**
* Recursively squeeze a multi dimensional array
*
@param
{
Array
} array
*
@param
{
number
} dims Required number of dimensions
*
@param
{
number
} dim Current dimension
*
@returns
{
Array | *
} Returns the squeezed array
*
@private
*/
function
_squeeze
(
array
,
dims
,
dim
)
{
let
i
,
ii
if
(
dim
<
dims
)
{
const
next
=
dim
+
1
for
(
i
=
0
,
ii
=
array
.
length
;
i
<
ii
;
i
++
)
{
array
[
i
]
=
_squeeze
(
array
[
i
]
,
dims
,
next
)
}
}
else
{
while
(
Array
.
isArray
(
array
)
)
{
array
=
array
[
0
]
}
}
return
array
}
/**
* Unsqueeze a multi dimensional array: add dimensions when missing
*
* Paramter `size` will be mutated to match the new, unqueezed matrix size.
*
*
@param
{
Array
} array
*
@param
{
number
} dims Desired number of dimensions of the array
*
@param
{
number
} [outer] Number of outer dimensions to be added
*
@param
{
Array
} [size] Current size of array.
*
@returns
{
Array
} returns the array itself
*
@private
*/
export
function
unsqueeze
(
array
,
dims
,
outer
,
size
)
{
const
s
=
size
||
arraySize
(
array
)
// unsqueeze outer dimensions
if
(
outer
)
{
for
(
let
i
=
0
;
i
<
outer
;
i
++
)
{
array
=
[
array
]
s
.
unshift
(
1
)
}
}
// unsqueeze inner dimensions
array
=
_unsqueeze
(
array
,
dims
,
0
)
while
(
s
.
length
<
dims
)
{
s
.
push
(
1
)
}
return
array
}
/**
* Recursively unsqueeze a multi dimensional array
*
@param
{
Array
} array
*
@param
{
number
} dims Required number of dimensions
*
@param
{
number
} dim Current dimension
*
@returns
{
Array | *
} Returns the squeezed array
*
@private
*/
function
_unsqueeze
(
array
,
dims
,
dim
)
{
let
i
,
ii
if
(
Array
.
isArray
(
array
)
)
{
const
next
=
dim
+
1
for
(
i
=
0
,
ii
=
array
.
length
;
i
<
ii
;
i
++
)
{
array
[
i
]
=
_unsqueeze
(
array
[
i
]
,
dims
,
next
)
}
}
else
{
for
(
let
d
=
dim
;
d
<
dims
;
d
++
)
{
array
=
[
array
]
}
}
return
array
}
/**
* Flatten a multi dimensional array, put all elements in a one dimensional
* array
*
@param
{
Array
} array A multi dimensional array
*
@return
{
Array
} The flattened array (1 dimensional)
*/
export
function
flatten
(
array
)
{
if
(
!
Array
.
isArray
(
array
)
)
{
// if not an array, return as is
return
array
}
const
flat
=
[
]
array
.
forEach
(
function
callback
(
value
)
{
if
(
Array
.
isArray
(
value
)
)
{
value
.
forEach
(
callback
)
// traverse through sub-arrays recursively
}
else
{
flat
.
push
(
value
)
}
}
)
return
flat
}
/**
* A safe map
*
@param
{
Array
} array
*
@param
{
function
} callback
*/
export
function
map
(
array
,
callback
)
{
return
Array
.
prototype
.
map
.
call
(
array
,
callback
)
}
/**
* A safe forEach
*
@param
{
Array
} array
*
@param
{
function
} callback
*/
export
function
forEach
(
array
,
callback
)
{
Array
.
prototype
.
forEach
.
call
(
array
,
callback
)
}
/**
* A safe filter
*
@param
{
Array
} array
*
@param
{
function
} callback
*/
export
function
filter
(
array
,
callback
)
{
if
(
arraySize
(
array
)
.
length
!==
1
)
{
throw
new
Error
(
'Only one dimensional matrices supported'
)
}
return
Array
.
prototype
.
filter
.
call
(
array
,
callback
)
}
/**
* Filter values in a callback given a regular expression
*
@param
{
Array
} array
*
@param
{
RegExp
} regexp
*
@return
{
Array
} Returns the filtered array
*
@private
*/
export
function
filterRegExp
(
array
,
regexp
)
{
if
(
arraySize
(
array
)
.
length
!==
1
)
{
throw
new
Error
(
'Only one dimensional matrices supported'
)
}
return
Array
.
prototype
.
filter
.
call
(
array
,
(
entry
)
=>
regexp
.
test
(
entry
)
)
}
/**
* A safe join
*
@param
{
Array
} array
*
@param
{
string
} separator
*/
export
function
join
(
array
,
separator
)
{
return
Array
.
prototype
.
join
.
call
(
array
,
separator
)
}
/**
* Assign a numeric identifier to every element of a sorted array
*
@param
{
Array
} a An array
*
@return
{
Array
} An array of objects containing the original value and its identifier
*/
export
function
identify
(
a
)
{
if
(
!
Array
.
isArray
(
a
)
)
{
throw
new
TypeError
(
'Array input expected'
)
}
if
(
a
.
length
===
0
)
{
return
a
}
const
b
=
[
]
let
count
=
0
b
[
0
]
=
{
value
:
a
[
0
]
,
identifier
:
0
}
for
(
let
i
=
1
;
i
<
a
.
length
;
i
++
)
{
if
(
a
[
i
]
===
a
[
i
-
1
]
)
{
count
++
}
else
{
count
=
0
}
b
.
push
(
{
value
:
a
[
i
]
,
identifier
:
count
}
)
}
return
b
}
/**
* Remove the numeric identifier from the elements
*
@param
{
array
} a An array
*
@return
{
array
} An array of values without identifiers
*/
export
function
generalize
(
a
)
{
if
(
!
Array
.
isArray
(
a
)
)
{
throw
new
TypeError
(
'Array input expected'
)
}
if
(
a
.
length
===
0
)
{
return
a
}
const
b
=
[
]
for
(
let
i
=
0
;
i
<
a
.
length
;
i
++
)
{
b
.
push
(
a
[
i
]
.
value
)
}
return
b
}
/**
* Check the datatype of a given object
* This is a low level implementation that should only be used by
* parent Matrix classes such as SparseMatrix or DenseMatrix
* This method does not validate Array Matrix shape
*
@param
{
Array
} array
*
@param
{
function
} typeOf Callback function to use to determine the type of a value
*
@return
{
string
}
*/
export
function
getArrayDataType
(
array
,
typeOf
)
{
let
type
// to hold type info
let
length
=
0
// to hold length value to ensure it has consistent sizes
for
(
let
i
=
0
;
i
<
array
.
length
;
i
++
)
{
const
item
=
array
[
i
]
const
isArray
=
Array
.
isArray
(
item
)
// Saving the target matrix row size
if
(
i
===
0
&&
isArray
)
{
length
=
item
.
length
}
// If the current item is an array but the length does not equal the targetVectorSize
if
(
isArray
&&
item
.
length
!==
length
)
{
return
undefined
}
const
itemType
=
isArray
?
getArrayDataType
(
item
,
typeOf
)
// recurse into a nested array
:
typeOf
(
item
)
if
(
type
===
undefined
)
{
type
=
itemType
// first item
}
else
if
(
type
!==
itemType
)
{
return
'mixed'
}
else
{
// we're good, everything has the same type so far
}
}
return
type
}
/**
* Return the last item from an array
*
@param
array
*
@returns
{
*
}
*/
export
function
last
(
array
)
{
return
array
[
array
.
length
-
1
]
}
/**
* Get all but the last element of array.
*/
export
function
initial
(
array
)
{
return
array
.
slice
(
0
,
array
.
length
-
1
)
}
/**
* Test whether an array or string contains an item
*
@param
{
Array | string
} array
*
@param
{
*
} item
*
@return
{
boolean
}
*/
export
function
contains
(
array
,
item
)
{
return
array
.
indexOf
(
item
)
!==
-
1
}
Back
|
FazBrowse Home
|
New Git URL