ArrayPrototype.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using Jint.Native.Object;
  2. using Jint.Runtime;
  3. using Jint.Runtime.Interop;
  4. namespace Jint.Native.Array
  5. {
  6. /// <summary>
  7. /// http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4
  8. /// </summary>
  9. public sealed class ArrayPrototype : ObjectInstance
  10. {
  11. private ArrayPrototype(Engine engine) : base(engine)
  12. {
  13. }
  14. public static ArrayPrototype CreatePrototypeObject(Engine engine, ArrayConstructor arrayConstructor)
  15. {
  16. var obj = new ArrayPrototype(engine) { Extensible = true };
  17. obj.FastAddProperty("constructor", arrayConstructor, false, false, false);
  18. return obj;
  19. }
  20. public void Configure()
  21. {
  22. // Array prototype functions
  23. FastAddProperty("push", new ClrFunctionInstance<ArrayInstance, object>(Engine, Push), false, false, false);
  24. FastAddProperty("pop", new ClrFunctionInstance<ArrayInstance, object>(Engine, Pop), false, false, false);
  25. }
  26. public object Push(object thisObject, object[] arguments)
  27. {
  28. var o = TypeConverter.ToObject(Engine, thisObject);
  29. var lenVal = o.Get("length");
  30. var n = TypeConverter.ToUint32(lenVal);
  31. foreach (var e in arguments)
  32. {
  33. o.Put(TypeConverter.ToString(n), e, true);
  34. n++;
  35. }
  36. o.Put("length", n, true);
  37. return n;
  38. }
  39. public object Pop(object thisObject, object[] arguments)
  40. {
  41. var o = TypeConverter.ToObject(Engine, thisObject);
  42. var lenVal = o.Get("length");
  43. var len = TypeConverter.ToUint32(lenVal);
  44. if (len == 0)
  45. {
  46. o.Put("length", 0, true);
  47. return Undefined.Instance;
  48. }
  49. else
  50. {
  51. var indx = TypeConverter.ToString(len - 1);
  52. var element = o.Get(indx);
  53. o.Delete(indx, true);
  54. o.Put("length", indx, true);
  55. return element;
  56. }
  57. }
  58. }
  59. }