Skip to content

Commit e9800e6

Browse files
committed
src: add iterator for Object
Refs: nodejs#830
1 parent ad76ad0 commit e9800e6

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

napi-inl.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1388,6 +1388,41 @@ inline void Object::AddFinalizer(Finalizer finalizeCallback,
13881388
}
13891389
}
13901390

1391+
inline Object::iterator::iterator(const Object* object, const Type type) {
1392+
_object = object;
1393+
_keys = object->GetPropertyNames();
1394+
_index = type == Type::BEGIN ? 0 : _keys.Length();
1395+
}
1396+
1397+
inline Object::iterator Napi::Object::begin() {
1398+
iterator it(this, Object::iterator::Type::BEGIN);
1399+
return it;
1400+
}
1401+
1402+
inline Object::iterator Napi::Object::end() {
1403+
iterator it(this, Object::iterator::Type::END);
1404+
return it;
1405+
}
1406+
1407+
inline Object::iterator& Object::iterator::operator++() {
1408+
++_index;
1409+
return *this;
1410+
}
1411+
1412+
inline bool Object::iterator::operator==(const iterator& other) const {
1413+
return _index == other._index;
1414+
}
1415+
1416+
inline bool Object::iterator::operator!=(const iterator& other) const {
1417+
return _index != other._index;
1418+
}
1419+
1420+
inline std::pair<Value, Value> Object::iterator::operator*() const {
1421+
const Value key = _keys.Get(_index);
1422+
const Value value = _object->Get(key);
1423+
return {key, value};
1424+
}
1425+
13911426
#if NAPI_VERSION >= 8
13921427
inline bool Object::Freeze() {
13931428
napi_status status = napi_object_freeze(_env, _value);

napi.h

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -772,6 +772,13 @@ namespace Napi {
772772
inline void AddFinalizer(Finalizer finalizeCallback,
773773
T* data,
774774
Hint* finalizeHint);
775+
776+
class iterator;
777+
778+
inline iterator begin();
779+
780+
inline iterator end();
781+
775782
#if NAPI_VERSION >= 8
776783
bool Freeze();
777784
bool Seal();
@@ -812,6 +819,29 @@ namespace Napi {
812819
uint32_t Length() const;
813820
};
814821

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

0 commit comments

Comments
 (0)