Skip to content

Commit 02186ee

Browse files
committed
src: add iterator for Object
Refs: #830
1 parent 77350ee commit 02186ee

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

napi-inl.h

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

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

napi.h

+30
Original file line numberDiff line numberDiff line change
@@ -776,6 +776,13 @@ namespace Napi {
776776
inline void AddFinalizer(Finalizer finalizeCallback,
777777
T* data,
778778
Hint* finalizeHint);
779+
780+
class iterator;
781+
782+
inline iterator begin();
783+
784+
inline iterator end();
785+
779786
#if NAPI_VERSION >= 8
780787
void Freeze();
781788
void Seal();
@@ -816,6 +823,29 @@ namespace Napi {
816823
uint32_t Length() const;
817824
};
818825

826+
class Object::iterator {
827+
private:
828+
enum class Type { BEGIN, END };
829+
830+
inline iterator(const Object* object, const Type type);
831+
832+
public:
833+
inline iterator& operator++();
834+
835+
inline bool operator==(const iterator& other) const;
836+
837+
inline bool operator!=(const iterator& other) const;
838+
839+
inline std::pair<Value, Value> operator*() const;
840+
841+
private:
842+
const Napi::Object* _object;
843+
Array _keys;
844+
uint32_t _index;
845+
846+
friend class Object;
847+
};
848+
819849
/// A JavaScript array buffer value.
820850
class ArrayBuffer : public Object {
821851
public:

0 commit comments

Comments
 (0)