1
0
mirror of https://github.com/robertkrimen/otto synced 2025-10-12 20:27:30 +08:00

Add Array.lastIndexOf (sdgoij)

This commit is contained in:
Robert Krimen 2013-06-16 14:55:12 -07:00
parent 6b4c8ec2b2
commit 2479aa628b
4 changed files with 68 additions and 0 deletions

View File

@ -340,3 +340,17 @@ func TestArray_indexOf(t *testing.T) {
abc.indexOf('c');
`, "2")
}
func TestArray_lastIndexOf(t *testing.T) {
Terst(t)
test := runTest()
test(`['a', 'b', 'c', 'b'].lastIndexOf('b')`, "3")
test(`['a', 'b', 'c', 'b'].lastIndexOf('b', 2)`, "1")
test(`['a', 'b', 'c', 'b'].lastIndexOf('b', -2)`, "1")
test(`
Object.prototype.lastIndexOf = Array.prototype.lastIndexOf;
var abc = {0: 'a', 1: 'b', 2: 'c', 3: 'b', length: 4};
abc.lastIndexOf('b');
`, "3")
}

View File

@ -482,3 +482,30 @@ func builtinArray_indexOf(call FunctionCall) Value {
}
return toValue(-1)
}
func builtinArray_lastIndexOf(call FunctionCall) Value {
thisObject, matchValue := call.thisObject(), call.Argument(0)
length := int64(toUint32(thisObject.get("length")))
index := length - 1
if len(call.ArgumentList) > 1 {
index = toInteger(call.Argument(1))
}
if 0 > index {
index += length
}
if index > length {
index = length - 1
} else if 0 > index {
return toValue(-1)
}
for ; index >= 0; index-- {
name := arrayIndexToString(uint(index))
if !thisObject.hasProperty(name) {
continue
}
if sameValue(matchValue, thisObject.get(name)) {
return toValue(uint32(index))
}
}
return toValue(-1)
}

1
inline
View File

@ -190,6 +190,7 @@ sub newContext {
"reverse", 0,
"sort", 0,
"indexOf", 1,
"lastIndexOf", 1,
);
return
".${class}Prototype =",

View File

@ -972,6 +972,25 @@ func _newContext(runtime *_runtime) {
call: _nativeCallFunction(builtinArray_indexOf),
},
}
lastIndexOf_function := &_object{
runtime: runtime,
class: "Function",
objectClass: _classObject,
prototype: runtime.Global.FunctionPrototype,
extensible: true,
property: map[string]_property{
"length": _property{
mode: 0,
value: Value{
_valueType: valueNumber,
value: 1,
},
},
},
value: _functionObject{
call: _nativeCallFunction(builtinArray_lastIndexOf),
},
}
isArray_function := &_object{
runtime: runtime,
class: "Function",
@ -1097,6 +1116,13 @@ func _newContext(runtime *_runtime) {
value: indexOf_function,
},
},
"lastIndexOf": _property{
mode: 0101,
value: Value{
_valueType: valueObject,
value: lastIndexOf_function,
},
},
},
}
runtime.Global.Array = &_object{