Skip to content

Commit 37e7c1b

Browse files
committed
Array: lastIndexOf implementation
1 parent 738dfd4 commit 37e7c1b

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

array.hpp

+13
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,19 @@ template <typename T> class Array
101101
return index < data_.size() ? index : -1;
102102
}
103103

104+
/**
105+
* Get the last index at which a given element can be found in the array
106+
* @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/lastIndexOf
107+
*
108+
* @param item Item last index of which we want to find out.
109+
* @returns Item's last index or -1 if item does not exist in the array.
110+
*/
111+
ssize_t lastIndexOf(const T & item) const {
112+
size_t lastIndex = std::find(data_.rbegin(), data_.rend(), item) - data_.rbegin();
113+
114+
return data_.size() - lastIndex - 1;
115+
}
116+
104117
/**
105118
* Push value to the end of array.
106119
* @see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/push

array.test.hpp

+6
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ class ArrayTest : public CppUnit::TestCase
3333
CPPUNIT_ASSERT( arr->indexOf(5) == 5 );
3434
}
3535

36+
void testLastIndexOf() {
37+
arr->push(1);
38+
CPPUNIT_ASSERT( arr->lastIndexOf(1) == 10 );
39+
}
40+
3641
void testFilter() {
3742
using std::tr1::bind;
3843
using std::tr1::placeholders::_1;
@@ -120,6 +125,7 @@ class ArrayTest : public CppUnit::TestCase
120125

121126
CPPUNIT_TEST( testLength );
122127
CPPUNIT_TEST( testIndexOf );
128+
CPPUNIT_TEST( testLastIndexOf );
123129
CPPUNIT_TEST( testFilter );
124130
CPPUNIT_TEST( testReduce );
125131
CPPUNIT_TEST( testEvery );

0 commit comments

Comments
 (0)