ccxvii / mujs

An embeddable Javascript interpreter in C.
http://mujs.com/
ISC License
794 stars 96 forks source link

Object.keys([2,3]) returns [] instead of ["0", "1"] #171

Closed avih closed 7 months ago

avih commented 1 year ago
print(Object.keys([2,3]));

prints nothing because keys returns an empty array, but it should return an array of the keys ["0", "1"].

As far as I can tell, this is a regression since 3f71a1c (optimized simple array).

avih commented 1 year ago

@sebras referred me to the pending patch here http://git.ghostscript.com/?p=user/tor/mujs.git;a=commitdiff;h=483bd4ffff410c828b8d87f7e08941d6bbb270ae :

--- a/jsobject.c
+++ b/jsobject.c
@@ -380,6 +380,13 @@ static void O_keys(js_State *J)
                        js_setindex(J, -2, i++);
                }
        }
+
+       if (obj->type == JS_CARRAY && obj->u.a.simple) {
+               for (k = 0; k < obj->u.a.flat_length; ++k) {
+                       js_pushnumber(J, k);
+                       js_setindex(J, -2, i++);
+               }
+       }
 }
 
 static void O_preventExtensions(js_State *J)

I think this patch produces an array of numbers, e.g. [0, 1...] instead of strings ["0", "1"...].

While at it, looks like the code just above above the patch which produces keys for a string object, like Object.keys(new String("foo")), has the same issue where it returns an array of numbers instead of strings: https://github.com/ccxvii/mujs/blob/7d9888b739040b9d58f1d6d0e42df98975b86d92/jsobject.c#L379-L384

avih commented 1 year ago

More while at it regarding Object.keys, seems like Object.keys([1,,2]) is non-flat (OK so far), returns ["0", "1", "2"], but Firefox returns ["0", "2"].

I don't know whether that's an ES5.1 vs newer JS version, but if not, then it's another issue.

EDIT: actually, Object.keys([1,,2]) currently returns [] (empty - bug). The results above of ["0", "1", "2"] are before the flat-array commit (also a bug).