From aae87a711e9fc8443ddb865f7792f3598b3bed36 Mon Sep 17 00:00:00 2001 From: Darshan Sen Date: Fri, 12 Mar 2021 22:18:01 +0530 Subject: [PATCH] src: add iterator for Object Refs: https://github.com/nodejs/node-addon-api/issues/830 --- napi-inl.h | 31 +++++++++++++++++++++++++++++++ napi.h | 24 ++++++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/napi-inl.h b/napi-inl.h index b12ec4ede..78949a93a 100644 --- a/napi-inl.h +++ b/napi-inl.h @@ -1378,6 +1378,37 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback, } } +Object::iterator::iterator(Object *object, uint32_t index) { + _object = object; + _index = index; + _keys = object->GetPropertyNames(); +} + +Object::iterator Napi::Object::begin() { + iterator it(this, 0); + return it; +} + +Object::iterator Napi::Object::end() { + iterator it(this, GetPropertyNames().Length()); + return it; +} + +Object::iterator Object::iterator::operator ++() { + ++_index; + return *this; +} + +bool Object::iterator::operator !=(iterator other) { + return _index != other._index; +} + +Value Object::iterator::operator *() { + Value key = _keys[_index].Value(); // Don't know how to convert this yet + Object object = *_object; + return object[key]; +} + //////////////////////////////////////////////////////////////////////////////// // External class //////////////////////////////////////////////////////////////////////////////// diff --git a/napi.h b/napi.h index 485176157..a8e1d9e4c 100644 --- a/napi.h +++ b/napi.h @@ -742,6 +742,12 @@ namespace Napi { inline void AddFinalizer(Finalizer finalizeCallback, T* data, Hint* finalizeHint); + + class iterator; + + iterator begin(); + + iterator end(); }; template @@ -778,6 +784,24 @@ namespace Napi { uint32_t Length() const; }; + class Object::iterator { + public: + iterator(Object *object, uint32_t index); + + iterator operator ++(); + + bool operator !=(iterator other); + + Value operator *(); + + private: + Napi::Object *_object; + uint32_t _index; + Array _keys; + + friend class Object; + }; + /// A JavaScript array buffer value. class ArrayBuffer : public Object { public: