Coerce findLastIndex and lastIndexOf fromIndex parameter to integer (#4440)

* Enable lastIndexOf, findLast and findLastIndex

* Coerce findLastIndex fromIndex parameter to integer

* Coerce lastIndexOf fromIndex parameter to integer
This commit is contained in:
Luiz Américo
2019-08-24 13:44:00 -03:00
committed by John-David Dalton
parent ed4b3a2ddb
commit 3ebb38d389
4 changed files with 15 additions and 4 deletions

View File

@@ -1,4 +1,5 @@
import baseFindIndex from './.internal/baseFindIndex.js'
import toInteger from './toInteger.js'
/**
* This method is like `findIndex` except that it iterates over elements
@@ -29,9 +30,10 @@ function findLastIndex(array, predicate, fromIndex) {
}
let index = length - 1
if (fromIndex !== undefined) {
index = toInteger(fromIndex)
index = fromIndex < 0
? Math.max(length + fromIndex, 0)
: Math.min(fromIndex, length - 1)
? Math.max(length + index, 0)
: Math.min(index, length - 1)
}
return baseFindIndex(array, predicate, index, true)
}

View File

@@ -1,6 +1,7 @@
import baseFindIndex from './.internal/baseFindIndex.js'
import baseIsNaN from './.internal/baseIsNaN.js'
import strictLastIndexOf from './.internal/strictLastIndexOf.js'
import toInteger from './toInteger.js'
/**
* This method is like `indexOf` except that it iterates over elements of
@@ -28,6 +29,7 @@ function lastIndexOf(array, value, fromIndex) {
}
let index = length
if (fromIndex !== undefined) {
index = toInteger(fromIndex)
index = index < 0 ? Math.max(length + index, 0) : Math.min(index, length - 1)
}
return value === value

View File

@@ -1,11 +1,18 @@
import assert from 'assert';
import lodashStable from 'lodash';
import { _, identity, stubZero, falsey } from './utils.js';
import { identity, stubZero, falsey } from './utils.js';
import findLastIndex from '../findLastIndex.js';
import lastIndexOf from '../lastIndexOf.js';
const methods = {
findLastIndex,
lastIndexOf
};
describe('findLastIndex and lastIndexOf', function() {
lodashStable.each(['findLastIndex', 'lastIndexOf'], function(methodName) {
var array = [1, 2, 3, 1, 2, 3],
func = _[methodName],
func = methods[methodName],
resolve = methodName == 'findLastIndex' ? lodashStable.curry(lodashStable.eq) : identity;
it('`_.' + methodName + '` should return the index of the last matched value', function() {