[d565449] | 1 | 'use strict';
|
---|
| 2 |
|
---|
| 3 | var $TypeError = require('es-errors/type');
|
---|
[79a0317] | 4 | var isInteger = require('math-intrinsics/isInteger');
|
---|
[d565449] | 5 |
|
---|
| 6 | var Call = require('./Call');
|
---|
| 7 | var Get = require('./Get');
|
---|
| 8 | var ToBoolean = require('./ToBoolean');
|
---|
| 9 | var IsCallable = require('./IsCallable');
|
---|
| 10 | var ToString = require('./ToString');
|
---|
| 11 |
|
---|
[79a0317] | 12 | var isObject = require('../helpers/isObject');
|
---|
| 13 |
|
---|
| 14 | // https://262.ecma-international.org/14.0/#sec-findviapredicate
|
---|
[d565449] | 15 |
|
---|
| 16 | module.exports = function FindViaPredicate(O, len, direction, predicate, thisArg) {
|
---|
[79a0317] | 17 | if (!isObject(O)) {
|
---|
[d565449] | 18 | throw new $TypeError('Assertion failed: Type(O) is not Object');
|
---|
| 19 | }
|
---|
| 20 | if (!isInteger(len) || len < 0) {
|
---|
| 21 | throw new $TypeError('Assertion failed: len must be a non-negative integer');
|
---|
| 22 | }
|
---|
| 23 | if (direction !== 'ascending' && direction !== 'descending') {
|
---|
| 24 | throw new $TypeError('Assertion failed: direction must be "ascending" or "descending"');
|
---|
| 25 | }
|
---|
| 26 |
|
---|
| 27 | if (!IsCallable(predicate)) {
|
---|
| 28 | throw new $TypeError('predicate must be callable'); // step 1
|
---|
| 29 | }
|
---|
| 30 |
|
---|
| 31 | for ( // steps 2-4
|
---|
| 32 | var k = direction === 'ascending' ? 0 : len - 1;
|
---|
| 33 | direction === 'ascending' ? k < len : k >= 0;
|
---|
| 34 | k += 1
|
---|
| 35 | ) {
|
---|
| 36 | var Pk = ToString(k); // step 4.a
|
---|
| 37 | var kValue = Get(O, Pk); // step 4.c
|
---|
| 38 | var testResult = Call(predicate, thisArg, [kValue, k, O]); // step 4.d
|
---|
| 39 | if (ToBoolean(testResult)) {
|
---|
| 40 | return { '[[Index]]': k, '[[Value]]': kValue }; // step 4.e
|
---|
| 41 | }
|
---|
| 42 | }
|
---|
| 43 | return { '[[Index]]': -1, '[[Value]]': void undefined }; // step 5
|
---|
| 44 | };
|
---|