Skip to content

Commit aae87a7

Browse files
committed
src: add iterator for Object
Refs: nodejs#830
1 parent 74ab50c commit aae87a7

File tree

2 files changed

+55
-0
lines changed

2 files changed

+55
-0
lines changed

napi-inl.h

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1378,6 +1378,37 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback,
13781378
}
13791379
}
13801380

1381+
Object::iterator::iterator(Object *object, uint32_t index) {
1382+
_object = object;
1383+
_index = index;
1384+
_keys = object->GetPropertyNames();
1385+
}
1386+
1387+
Object::iterator Napi::Object::begin() {
1388+
iterator it(this, 0);
1389+
return it;
1390+
}
1391+
1392+
Object::iterator Napi::Object::end() {
1393+
iterator it(this, GetPropertyNames().Length());
1394+
return it;
1395+
}
1396+
1397+
Object::iterator Object::iterator::operator ++() {
1398+
++_index;
1399+
return *this;
1400+
}
1401+
1402+
bool Object::iterator::operator !=(iterator other) {
1403+
return _index != other._index;
1404+
}
1405+
1406+
Value Object::iterator::operator *() {
1407+
Value key = _keys[_index].Value(); // Don't know how to convert this yet
1408+
Object object = *_object;
1409+
return object[key];
1410+
}
1411+
13811412
////////////////////////////////////////////////////////////////////////////////
13821413
// External class
13831414
////////////////////////////////////////////////////////////////////////////////

napi.h

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -742,6 +742,12 @@ namespace Napi {
742742
inline void AddFinalizer(Finalizer finalizeCallback,
743743
T* data,
744744
Hint* finalizeHint);
745+
746+
class iterator;
747+
748+
iterator begin();
749+
750+
iterator end();
745751
};
746752

747753
template <typename T>
@@ -778,6 +784,24 @@ namespace Napi {
778784
uint32_t Length() const;
779785
};
780786

787+
class Object::iterator {
788+
public:
789+
iterator(Object *object, uint32_t index);
790+
791+
iterator operator ++();
792+
793+
bool operator !=(iterator other);
794+
795+
Value operator *();
796+
797+
private:
798+
Napi::Object *_object;
799+
uint32_t _index;
800+
Array _keys;
801+
802+
friend class Object;
803+
};
804+
781805
/// A JavaScript array buffer value.
782806
class ArrayBuffer : public Object {
783807
public:

0 commit comments

Comments
 (0)