Skip to content

Commit 490a387

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

File tree

2 files changed

+66
-0
lines changed

2 files changed

+66
-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+
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+
Object::iterator Napi::Object::begin() {
1388+
iterator it(this, Object::iterator::Type::BEGIN);
1389+
return it;
1390+
}
1391+
1392+
Object::iterator Napi::Object::end() {
1393+
iterator it(this, Object::iterator::Type::END);
1394+
return it;
1395+
}
1396+
1397+
Object::iterator& Object::iterator::operator ++() {
1398+
++_index;
1399+
return *this;
1400+
}
1401+
1402+
bool Object::iterator::operator ==(const iterator& other) const {
1403+
return _index == other._index;
1404+
}
1405+
1406+
bool Object::iterator::operator !=(const iterator& other) const {
1407+
return _index != other._index;
1408+
}
1409+
1410+
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

+31
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,31 @@ namespace Napi {
778784
uint32_t Length() const;
779785
};
780786

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

0 commit comments

Comments
 (0)