mh-two-thousand-and-two
2024-04-12 7fc6dbf547b8899d949b67cdec36b96a7d1701c7
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
'use strict';
 
var $TypeError = require('es-errors/type');
 
var Call = require('./Call');
var Get = require('./Get');
var ToBoolean = require('./ToBoolean');
var IsCallable = require('./IsCallable');
var ToString = require('./ToString');
var Type = require('./Type');
 
var isInteger = require('../helpers/isInteger');
 
module.exports = function FindViaPredicate(O, len, direction, predicate, thisArg) {
    if (Type(O) !== 'Object') {
        throw new $TypeError('Assertion failed: Type(O) is not Object');
    }
    if (!isInteger(len) || len < 0) {
        throw new $TypeError('Assertion failed: len must be a non-negative integer');
    }
    if (direction !== 'ascending' && direction !== 'descending') {
        throw new $TypeError('Assertion failed: direction must be "ascending" or "descending"');
    }
 
    if (!IsCallable(predicate)) {
        throw new $TypeError('predicate must be callable'); // step 1
    }
 
    for ( // steps 2-4
        var k = direction === 'ascending' ? 0 : len - 1;
        direction === 'ascending' ? k < len : k >= 0;
        k += 1
    ) {
        var Pk = ToString(k); // step 4.a
        var kValue = Get(O, Pk); // step 4.c
        var testResult = Call(predicate, thisArg, [kValue, k, O]); // step 4.d
        if (ToBoolean(testResult)) {
            return { '[[Index]]': k, '[[Value]]': kValue }; // step 4.e
        }
    }
    return { '[[Index]]': -1, '[[Value]]': void undefined }; // step 5
};