/
util.js
2090 lines (1767 loc) · 51 KB
/
util.js
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
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-
Utility functions
=================
The `up.util` module contains functions to facilitate the work with basic JavaScript
values like lists, strings or functions.
You will recognize many functions form other utility libraries like [Lodash](https://lodash.com/).
While feature parity with Lodash is not a goal of `up.util`, you might find it sufficient
to not include another library in your asset bundle.
@see url-patterns
@module up.util
*/
up.util = (function() {
/*-
A function that does nothing.
@function up.util.noop
@experimental
*/
function noop() {
}
/*-
A function that returns a resolved promise.
@function up.util.asyncNoop
@internal
*/
function asyncNoop(){
return Promise.resolve()
}
/*-
Ensures that the given function can only be called a single time.
Subsequent calls will return the return value of the first call.
Note that this is a simple implementation that
doesn't distinguish between argument lists.
@function up.util.memoize
@internal
*/
function memoize(func) {
let cachedValue, cached
return function(...args) {
if (cached) {
return cachedValue
} else {
cached = true
return cachedValue = func.apply(this, args)
}
}
}
const NORMALIZE_URL_DEFAULTS = {
host: 'cross-domain',
}
/*-
Returns a normalized version of the given URL string.
Two URLs that point to the same resource should normalize to the same string.
### Comparing normalized URLs
The main purpose of this function is to normalize two URLs for string comparison:
```js
up.util.normalizeURL('http://current-host/path') === up.util.normalizeURL('/path') // => true
```
By default the hostname is only included if it points to a different origin:
```js
up.util.normalizeURL('http://current-host/path') // => '/path'
up.util.normalizeURL('http://other-host/path') // => 'http://other-host/path'
```
Relative paths are normalized to absolute paths:
```js
up.util.normalizeURL('index.html') // => '/path/index.html'
```
### Excluding URL components
You may pass options to exclude URL components from the normalized string:
```js
up.util.normalizeURL('/foo?query=bar', { query: false }) => '/foo'
up.util.normalizeURL('/bar#hash', { hash: false }) => '/bar'
```
### Limitations
- Username and password are always omitted from the normalized URL.
- Only `http` and `https` schemes are supported.
@function up.util.normalizeURL
@param {string|URL} the URL to normalize
@param {boolean} [options.host='cross-domain']
Whether to include protocol, hostname and port in the normalized URL.
When set to `'cross-domain'` (the default), the host is only included if it differ's from the page's hostname.
The port is omitted if the port is the standard port for the given protocol, e.g. `:443` for `https://`.
@param {boolean} [options.hash=true]
Whether to include an `#hash` anchor in the normalized URL.
@param {boolean} [options.search=true]
Whether to include a `?query` string in the normalized URL.
@param {boolean} [options.trailingSlash=true]
Whether to include a trailing slash from the pathname.
@return {string}
The normalized URL.
@experimental
*/
function normalizeURL(url, options) {
options = newOptions(options, NORMALIZE_URL_DEFAULTS)
const parts = parseURL(url)
let normalized = ''
if (options.host === 'cross-domain') {
options.host = isCrossOrigin(parts)
}
if (options.host) {
normalized += parts.protocol + "//" + parts.host
}
let { pathname } = parts
if (options.trailingSlash === false && pathname !== '/') {
pathname = pathname.replace(/\/$/, '')
}
normalized += pathname
if (options.search !== false) {
normalized += parts.search
}
if (options.hash !== false) {
normalized += parts.hash
}
return normalized
}
function matchURLs(leftURL, rightURL) {
return normalizeURL(leftURL) === normalizeURL(rightURL)
}
// We're calling isCrossOrigin() a lot.
// Accessing location.protocol and location.hostname every time
// is much slower than comparing cached strings.
// https://jsben.ch/kBATt
const APP_PROTOCOL = location.protocol
const APP_HOSTNAME = location.hostname
function isCrossOrigin(urlOrAnchor) {
// If the given URL does not contain a hostname we know it cannot be cross-origin.
// In that case we don't need to parse the URL.
if (isString(urlOrAnchor) && (urlOrAnchor.indexOf('//') === -1)) {
return false
}
const parts = parseURL(urlOrAnchor)
return (APP_HOSTNAME !== parts.hostname) || (APP_PROTOCOL !== parts.protocol)
}
/*-
Parses the given URL into components such as hostname and path.
If the given URL is not fully qualified, it is assumed to be relative
to the current page.
### Example
```js
let parsed = up.util.parseURL('/path?foo=value')
parsed.pathname // => '/path'
parsed.search // => '/?foo=value'
parsed.hash // => ''
```
@function up.util.parseURL
@param {string|URL} the URL to parse
@return {Object}
The parsed URL as an object with
`{ protocol, hostname, port, pathname, search, hash }` properties.
@stable
*/
function parseURL(url) {
if (url.pathname) {
return url
}
// We would prefer to use `new URL(url, location.href)` here, but that is 30% slower
// than creating a link (see benchmark at https://jsbench.me/l7l2x9cruf/1).
// We're parsing a *lot* of URLs for [up-active], so this matters.
let link = document.createElement('a')
link.href = url
return link
}
/*-
@function up.util.normalizeMethod
@internal
*/
function normalizeMethod(method) {
return method ? method.toUpperCase() : 'GET'
}
/*-
@function up.util.methodAllowsPayload
@internal
*/
function methodAllowsPayload(method) {
return (method !== 'GET') && (method !== 'HEAD')
}
function iteratee(block) {
if (isString(block)) {
return item => item[block]
} else {
return block
}
}
/*-
Translate all items in a [list](/up.util.isList) to new array of items.
@function up.util.map
@param {List|Iterator} list
@param {Function(element, index): any|string} block
A function that will be called with each element and (optional) iteration index.
You can also pass a property name as a String,
which will be collected from each item in the list.
@return {Array}
A new array containing the result of each function call.
@stable
*/
function map(list, block) {
if (list.length === 0) { return [] }
block = iteratee(block)
let mapped = []
let i = 0
for (let item of list) {
mapped.push(block(item, i++))
}
return mapped
}
/*-
@function up.util.mapObject
@internal
*/
function mapObject(array, pairer) {
const merger = function(object, pair) {
object[pair[0]] = pair[1]
return object
}
return map(array, pairer).reduce(merger, {})
}
/*-
Calls the given function for each element (and, optional, index)
of the given [list](/up.util.isList) or iterator.
@function up.util.each
@param {List|Iterator} list
@param {Function(element, index)} block
A function that will be called with each element and (optional) iteration index.
@stable
*/
function each(array, block) {
// note that the native Array.forEach is very slow (https://jsperf.com/fast-array-foreach)
let i = 0
for (let item of array) {
block(item, i++)
}
}
/*-
Returns whether the given argument is `null`.
@function up.util.isNull
@param object
@return {boolean}
@stable
*/
function isNull(object) {
return object === null
}
/*-
Returns whether the given argument is `undefined`.
@function up.util.isUndefined
@param object
@return {boolean}
@stable
*/
function isUndefined(object) {
return object === undefined
}
/*-
Returns whether the given argument is not `undefined`.
@function up.util.isDefined
@param object
@return {boolean}
@stable
*/
const isDefined = negate(isUndefined)
/*-
Returns whether the given argument is either `undefined` or `null`.
Note that empty strings or zero are *not* considered to be "missing".
For the opposite of `up.util.isMissing()` see [`up.util.isGiven()`](/up.util.isGiven).
@function up.util.isMissing
@param object
@return {boolean}
@stable
*/
function isMissing(object) {
return isUndefined(object) || isNull(object)
}
/*-
Returns whether the given argument is neither `undefined` nor `null`.
For the opposite of `up.util.isGiven()` see [`up.util.isMissing()`](/up.util.isMissing).
> [IMPORTANT]
> Unpoly's concept of "given" does not correspond to JavaScript's concept of [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy).
> Empty strings or the number zero are not truthy, but *are* considered to be "given".
@function up.util.isGiven
@param object
@return {boolean}
@stable
*/
const isGiven = negate(isMissing)
// isNan = (object) ->
// isNumber(value) && value != +value
/*-
Return whether the given argument is considered to be blank.
By default, this function returns `true` for:
- `undefined`
- `null`
- Empty strings
- Empty arrays
- A plain object without own enumerable properties
All other arguments return `false`.
To check implement blank-ness checks for user-defined classes,
see `up.util.isBlank.key`.
@function up.util.isBlank
@param value
The value is to check.
@return {boolean}
Whether the value is blank.
@stable
*/
function isBlank(value) {
if (isMissing(value)) {
return true
}
if (isObject(value) && value[isBlank.key]) {
return value[isBlank.key]()
}
if (isString(value) || isList(value)) {
return value.length === 0
}
if (isOptions(value)) {
return Object.keys(value).length === 0
}
return false
}
/*-
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.isBlank()` protocol.
### Example
We have a user-defined `Account` class that we want to use with `up.util.isBlank()`:
```js
class Account {
constructor(email) {
this.email = email
}
[up.util.isBlank.key]() {
return up.util.isBlank(this.email)
}
}
```
> [NOTE]
> The protocol method is not actually named `'up.util.isBlank.key'`.
> Instead it is named after the *value* of the `up.util.isBlank.key` property.
> To do so, the code sample above is using a
> [computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
> in square brackets.
We may now use `Account` instances with `up.util.isBlank()`:
```js
let foo = new Account('foo@foo.com')
let bar = new Account('')
console.log(up.util.isBlank(foo)) // prints false
console.log(up.util.isBlank(bar)) // prints true
```
@property up.util.isBlank.key
@experimental
*/
isBlank.key = 'up.util.isBlank'
/*-
Returns the given argument if the argument is [present](/up.util.isPresent),
otherwise returns `undefined`.
@function up.util.presence
@param value
@param {Function(value): boolean} [tester=up.util.isPresent]
The function that will be used to test whether the argument is present.
@return {any|undefined}
@stable
*/
function presence(value, tester = isPresent) {
if (tester(value)) {
return value
}
}
/*-
Returns whether the given argument is not [blank](/up.util.isBlank).
@function up.util.isPresent
@param object
@return {boolean}
@stable
*/
const isPresent = negate(isBlank)
/*-
Returns whether the given argument is a function.
@function up.util.isFunction
@param object
@return {boolean}
@stable
*/
function isFunction(object) {
return typeof(object) === 'function'
}
/*-
Returns whether the given argument is a string.
@function up.util.isString
@param object
@return {boolean}
@stable
*/
function isString(object) {
return (typeof(object) === 'string') || object instanceof String
}
/*-
Returns whether the given argument is a boolean value.
@function up.util.isBoolean
@param object
@return {boolean}
@stable
*/
function isBoolean(object) {
return (typeof(object) === 'boolean') || object instanceof Boolean
}
/*-
Returns whether the given argument is a number.
Note that this will check the argument's *type*.
It will return `false` for a string like `"123"`.
@function up.util.isNumber
@param object
@return {boolean}
@stable
*/
function isNumber(object) {
return (typeof(object) === 'number') || object instanceof Number
}
/*-
Returns whether the given argument is an options hash,
Differently from [`up.util.isObject()`], this returns false for
functions, jQuery collections, promises, `FormData` instances and arrays.
@function up.util.isOptions
@param object
@return {boolean}
@internal
*/
function isOptions(object) {
return (typeof(object) === 'object') && !isNull(object) && (isUndefined(object.constructor) || (object.constructor === Object))
}
/*-
Returns whether the given argument is an object.
This also returns `true` for functions, which may behave like objects in JavaScript.
@function up.util.isObject
@param object
@return {boolean}
@stable
*/
function isObject(object) {
const typeOfResult = typeof(object)
return ((typeOfResult === 'object') && !isNull(object)) || (typeOfResult === 'function')
}
/*-
Returns whether the given argument is a [DOM element](https://developer.mozilla.org/de/docs/Web/API/Element).
@function up.util.isElement
@param object
@return {boolean}
@stable
*/
function isElement(object) {
return object instanceof Element
}
/*-
Returns whether the given argument is a [regular expression](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp).
@function up.util.isRegExp
@param object
@return {boolean}
@internal
*/
function isRegExp(object) {
return object instanceof RegExp
}
/*-
Returns whether the given argument is an error instance.
@function up.util.isError
@param object
@return {boolean}
@internal
*/
function isError(object) {
return object instanceof Error
}
/*-
Returns whether the given argument is a [jQuery collection](https://learn.jquery.com/using-jquery-core/jquery-object/).
@function up.util.isJQuery
@param object
@return {boolean}
@stable
*/
function isJQuery(object) {
return up.browser.canJQuery() && object instanceof jQuery
}
/*-
@function up.util.isElementish
@param object
@return {boolean}
@internal
*/
function isElementish(object) {
return !!(object && (object.addEventListener || object[0]?.addEventListener))
}
/*-
Returns whether the given argument is an object with a `then` method.
@function up.util.isPromise
@param object
@return {boolean}
@stable
*/
function isPromise(object) {
return isObject(object) && isFunction(object.then)
}
/*-
Returns whether the given argument is an array.
@function up.util.isArray
@param object
@return {boolean}
@stable
*/
// https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
const { isArray } = Array
/*-
Returns whether the given argument is a `FormData` instance.
Always returns `false` in browsers that don't support `FormData`.
@function up.util.isFormData
@param object
@return {boolean}
@internal
*/
function isFormData(object) {
return object instanceof FormData
}
/*-
Converts the given [array-like value](/up.util.isList) into an array.
If the given value is already an array, it is returned unchanged.
@function up.util.toArray
@param object
@return {Array}
@stable
*/
function toArray(value) {
return isArray(value) ? value : copyArrayLike(value)
}
/*-
Returns whether the given argument is an array-like value.
Return true for `Array`, a
[`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList),
the [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments)
or a jQuery collection.
Use [`up.util.isArray()`](/up.util.isArray) to test whether a value is an actual `Array`.
@function up.util.isList
@param value
@return {boolean}
@stable
*/
function isList(value) {
return isArray(value) ||
isNodeList(value) ||
isArguments(value) ||
isJQuery(value) ||
isHTMLCollection(value)
}
/*-
Returns whether the given value is a [`NodeList`](https://developer.mozilla.org/en-US/docs/Web/API/NodeList).
`NodeLists` are array-like objects returned by [`document.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/querySelectorAll).
@function up.util.isNodeList
@param value
@return {boolean}
@internal
*/
function isNodeList(value) {
return value instanceof NodeList
}
function isHTMLCollection(value) {
return value instanceof HTMLCollection
}
/*-
Returns whether the given value is an [arguments object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments).
@function up.util.isArguments
@param value
@return {boolean}
@internal
*/
function isArguments(value) {
return Object.prototype.toString.call(value) === '[object Arguments]'
}
function nullToUndefined(value) {
if (!isNull(value)) {
return value
}
}
/*-
Returns the given value if it is [array-like](/up.util.isList), otherwise
returns an array with the given value as its only element.
Returns an empty array if called with `null` or `undefined`.
### Example
```js
up.util.wrapList([1, 2, 3]) // => [1, 2, 3]
up.util.wrapList('foo') // => ['foo']
up.util.wrapList(undefined) // => []
up.util.wrapList(null) // => []
```
@function up.util.wrapList
@param {any} value
@return {Array|NodeList|jQuery}
@experimental
*/
function wrapList(value) {
if (isList(value)) {
return value
} else if (isMissing(value)) {
return []
} else {
return [value]
}
}
/*-
Returns a shallow copy of the given value.
### Copying protocol
- By default `up.util.copy()` can copy [array-like values](/up.util.isList),
plain objects and `Date` instances.
- Array-like objects are copied into new arrays.
- Unsupported types of values are returned unchanged.
- To make the copying protocol work with user-defined class,
see `up.util.copy.key`.
- Immutable objects, like strings or numbers, do not need to be copied.
@function up.util.copy
@param {any} object
@return {any}
@stable
*/
function copy(value) {
if (isObject(value) && value[copy.key]) {
value = value[copy.key]()
} else if (isList(value)) {
value = copyArrayLike(value)
} else if (isOptions(value)) {
value = Object.assign({}, value)
}
return value
}
function copyArrayLike(arrayLike) {
return Array.prototype.slice.call(arrayLike)
}
/*-
This property contains the name of a method that user-defined classes
may implement to hook into the `up.util.copy()` protocol.
### Example
We have a user-defined `Account` class that we want to use with `up.util.copy()`:
```js
class Account {
constructor(email) {
this.email = email
}
[up.util.copy.key]() {
return new Account(this.email)
}
}
```
> [NOTE]
> The protocol method is not actually named `'up.util.copy.key'`.
> Instead it is named after the *value* of the `up.util.copy.key` property.
> To do so, the code sample above is using a
> [computed property name](https://medium.com/front-end-weekly/javascript-object-creation-356e504173a8)
> in square brackets.
We may now use `Account` instances with `up.util.copy()`:
```
original = new User('foo@foo.com')
copy = up.util.copy(original)
console.log(copy.email) // prints 'foo@foo.com'
original.email = 'bar@bar.com' // change the original
console.log(copy.email) // still prints 'foo@foo.com'
```
@property up.util.copy.key
@param {string} key
@experimental
*/
copy.key = 'up.util.copy'
// Implement up.util.copy protocol for Date
Date.prototype[copy.key] = function() { return new Date(+this) }
/*-
Creates a new object by merging together the properties from the given objects.
### Example
```js
let a = { a: '1', b: '2' }
let b = { b: '3', c: '4' }
up.util.merge(a, b) // => { a: '1', b: '3', c: '4' }
```
@function up.util.merge
@param {Array<Object>} sources...
@return Object
@stable
*/
function merge(...sources) {
return Object.assign({}, ...sources)
}
/*-
@function up.util.mergeDefined
@param {Array<Object>} sources...
@return Object
@internal
*/
function mergeDefined(...sources) {
const result = {}
for (let source of sources) {
if (source) {
for (let key in source) {
const value = source[key]
if (isDefined(value)) {
result[key] = value
}
}
}
}
return result
}
/*-
Creates an options hash from the given argument and some defaults.
The semantics of this function are confusing.
We want to get rid of this in the future.
@function up.util.options
@param {Object} object
@param {Object} [defaults]
@return {Object}
@internal
*/
function newOptions(object, defaults) {
if (defaults) {
return merge(defaults, object)
} else if (object) {
return copy(object)
} else {
return {}
}
}
function parseArgIntoOptions(args, argKey) {
let options = extractOptions(args)
if (isDefined(args[0])) {
options = copy(options)
options[argKey] = args[0]
}
return options
}
/*-
Passes each element in the given [array-like value](/up.util.isList) to the given function.
Returns the first element for which the function returns a truthy value.
If no object matches, returns `undefined`.
@function up.util.find
@param {List<T>} list
@param {Function(value): boolean} tester
@return {T|undefined}
@stable
*/
function findInList(list, tester) {
tester = iteratee(tester)
let match
for (let element of list) {
if (tester(element)) {
match = element
break
}
}
return match
}
/*-
Returns whether the given function returns a truthy value
for any element in the given [array-like value](/up.util.isList).
@function up.util.some
@param {List} list
@param {Function(value, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@stable
*/
function some(list, tester) {
return !!findResult(list, tester)
}
/*-
Consecutively calls the given function which each element
in the given list. Returns the first truthy return value.
Returned `undefined` iff the function does not return a truthy
value for any element in the list.
@function up.util.findResult
@param {List|Iterator} list
@param {Function(element): any} tester
A function that will be called with each element and (optional) iteration index.
@return {any|undefined}
@experimental
*/
function findResult(list, tester) {
tester = iteratee(tester)
let i = 0
for (let item of list) {
const result = tester(item, i++)
if (result) {
return result
}
}
}
/*-
Returns whether the given function returns a truthy value
for all elements in the given [list](/up.util.isList) or iterator.
@function up.util.every
@param {List|Iterator} list
@param {Function(element, index): boolean} tester
A function that will be called with each element and (optional) iteration index.
@return {boolean}
@experimental
*/
function every(list, tester) {
tester = iteratee(tester)
let match = true
let i = 0
for (let item of list) {
if (!tester(item, i++)) {
match = false
break
}
}
return match
}
/*-
Returns all elements from the given [list](/up.util.isList) that are
neither `null` or `undefined`.
@function up.util.compact
@param {List<T>} list
@return {Array<T>}
@stable
*/
function compact(array) {
return filterList(array, isGiven)
}