Skip to content

Commit c046a43

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

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

napi-inl.h

+35
Original file line numberDiff line numberDiff line change
@@ -1378,6 +1378,41 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback,
13781378
}
13791379
}
13801380

1381+
inline Object::iterator::iterator(const Object* object, const Type type) {
1382+
_object = object;
1383+
_keys = object->GetPropertyNames();
1384+
_index = type == Type::BEGIN ? 0 : _keys.Length();
1385+
}
1386+
1387+
inline Object::iterator Napi::Object::begin() {
1388+
iterator it(this, Object::iterator::Type::BEGIN);
1389+
return it;
1390+
}
1391+
1392+
inline Object::iterator Napi::Object::end() {
1393+
iterator it(this, Object::iterator::Type::END);
1394+
return it;
1395+
}
1396+
1397+
inline Object::iterator& Object::iterator::operator++() {
1398+
++_index;
1399+
return *this;
1400+
}
1401+
1402+
inline bool Object::iterator::operator==(const iterator& other) const {
1403+
return _index == other._index;
1404+
}
1405+
1406+
inline bool Object::iterator::operator!=(const iterator& other) const {
1407+
return _index != other._index;
1408+
}
1409+
1410+
inline std::pair<Value, Value> Object::iterator::operator*() const {
1411+
const Value key = _keys.Get(_index);
1412+
const Value value = _object->Get(key);
1413+
return {key, value};
1414+
}
1415+
13811416
////////////////////////////////////////////////////////////////////////////////
13821417
// External class
13831418
////////////////////////////////////////////////////////////////////////////////

napi.h

+29
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+
inline iterator begin();
749+
750+
inline iterator end();
745751
};
746752

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

787+
class Object::iterator {
788+
private:
789+
enum class Type { BEGIN, END };
790+
791+
inline iterator(const Object* object, const Type type);
792+
793+
public:
794+
inline iterator& operator++();
795+
796+
inline bool operator==(const iterator& other) const;
797+
798+
inline bool operator!=(const iterator& other) const;
799+
800+
inline std::pair<Value, Value> operator*() const;
801+
802+
private:
803+
const Napi::Object* _object;
804+
Array _keys;
805+
uint32_t _index;
806+
807+
friend class Object;
808+
};
809+
781810
/// A JavaScript array buffer value.
782811
class ArrayBuffer : public Object {
783812
public:

0 commit comments

Comments
 (0)