forked from ramda/ramda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlastIndexOf.js
95 lines (82 loc) · 2.54 KB
/
lastIndexOf.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
var R = require('../source/index.js');
var eq = require('./shared/eq.js');
var {Just} = require('./shared/Maybe.js');
describe('lastIndexOf', function() {
it("returns a number indicating an object's last position in a list", function() {
var list = [0, 10, 20, 30, 0, 10, 20, 30, 0, 10];
eq(R.lastIndexOf(30, list), 7);
});
it('returns -1 if the object is not in the list', function() {
var list = [0, 10, 20, 30];
eq(R.lastIndexOf(40, list), -1);
});
var input = [1, 2, 3, 4, 5, 1];
it('returns the last index of the first item', function() {
eq(R.lastIndexOf(1, input), 5);
});
it('returns the index of the last item', function() {
eq(R.lastIndexOf(5, input), 4);
});
var list = ['a', 1, 'a'];
list[-2] = 'a'; // Throw a wrench in the gears by assigning a non-valid array index as object property.
it('finds a', function() {
eq(R.lastIndexOf('a', list), 2);
});
it('does not find c', function() {
eq(R.lastIndexOf('c', list), -1);
});
it('does not consider "1" equal to 1', function() {
eq(R.lastIndexOf('1', list), -1);
});
it('returns -1 for an empty array', function() {
eq(R.lastIndexOf('x', []), -1);
});
it('has R.equals semantics', function() {
eq(R.lastIndexOf(0, [-0]), -1);
eq(R.lastIndexOf(-0, [0]), -1);
eq(R.lastIndexOf(NaN, [NaN]), 0);
eq(R.lastIndexOf(new Just([42]), [new Just([42])]), 0);
});
it('dispatches to `lastIndexOf` method', function() {
function Empty() {}
Empty.prototype.lastIndexOf = R.always(-1);
function List(head, tail) {
this.head = head;
this.tail = tail;
}
List.prototype.lastIndexOf = function(x) {
var idx = this.tail.lastIndexOf(x);
return idx >= 0 ? 1 + idx : this.head === x ? 0 : -1;
};
var list = new List('b',
new List('a',
new List('n',
new List('a',
new List('n',
new List('a',
new Empty()
)
)
)
)
)
);
eq(R.lastIndexOf('a', 'banana'), 5);
eq(R.lastIndexOf('x', 'banana'), -1);
eq(R.lastIndexOf('a', list), 5);
eq(R.lastIndexOf('x', list), -1);
});
it('finds function, compared by identity', function() {
var f = function() {};
var g = function() {};
var list = [g, f, g, f];
eq(R.lastIndexOf(f, list), 3);
});
it('does not find function, compared by identity', function() {
var f = function() {};
var g = function() {};
var h = function() {};
var list = [g, f];
eq(R.lastIndexOf(h, list), -1);
});
});