From 2479aa628b681c3a58971d0ba4becb89223b691a Mon Sep 17 00:00:00 2001 From: Robert Krimen Date: Sun, 16 Jun 2013 14:55:12 -0700 Subject: [PATCH] Add Array.lastIndexOf (sdgoij) --- array_test.go | 14 ++++++++++++++ builtin_array.go | 27 +++++++++++++++++++++++++++ inline | 1 + inline.go | 26 ++++++++++++++++++++++++++ 4 files changed, 68 insertions(+) diff --git a/array_test.go b/array_test.go index 5514818..c2bf243 100644 --- a/array_test.go +++ b/array_test.go @@ -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") +} diff --git a/builtin_array.go b/builtin_array.go index 658217c..1597a82 100644 --- a/builtin_array.go +++ b/builtin_array.go @@ -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) +} diff --git a/inline b/inline index 1842cc7..fe7ff72 100755 --- a/inline +++ b/inline @@ -190,6 +190,7 @@ sub newContext { "reverse", 0, "sort", 0, "indexOf", 1, + "lastIndexOf", 1, ); return ".${class}Prototype =", diff --git a/inline.go b/inline.go index ce929c0..b7f8896 100644 --- a/inline.go +++ b/inline.go @@ -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{