Add API to return all keys of weak map.

This commit is contained in:
Cheng Zhao 2013-04-27 16:54:17 +08:00
parent b35946381b
commit 51db9494bd
2 changed files with 21 additions and 4 deletions

View file

@ -10,14 +10,14 @@ namespace atom {
namespace api { namespace api {
IDWeakMap::IDWeakMap() IDWeakMap::IDWeakMap()
: nextId_(0) { : next_id_(0) {
} }
IDWeakMap::~IDWeakMap() { IDWeakMap::~IDWeakMap() {
v8::Isolate* isolate = v8::Isolate::GetCurrent(); v8::Isolate* isolate = v8::Isolate::GetCurrent();
auto copied_map = map_; auto copied_map = map_;
for (auto el : copied_map) for (const auto& el : copied_map)
Erase(isolate, el.first); Erase(isolate, el.first);
} }
@ -35,7 +35,7 @@ void IDWeakMap::Erase(v8::Isolate* isolate, int key) {
} }
int IDWeakMap::GetNextID() { int IDWeakMap::GetNextID() {
return ++nextId_; return ++next_id_;
} }
// static // static
@ -102,6 +102,21 @@ v8::Handle<v8::Value> IDWeakMap::Has(const v8::Arguments& args) {
return v8::Boolean::New(obj->Has(key)); return v8::Boolean::New(obj->Has(key));
} }
// static
v8::Handle<v8::Value> IDWeakMap::Keys(const v8::Arguments& args) {
IDWeakMap* obj = ObjectWrap::Unwrap<IDWeakMap>(args.This());
v8::Handle<v8::Array> keys = v8::Array::New(obj->map_.size());
int i = 0;
for (const auto& el : obj->map_) {
keys->Set(i, v8::Integer::New(el.first));
++i;
}
return keys;
}
// static // static
v8::Handle<v8::Value> IDWeakMap::Remove(const v8::Arguments& args) { v8::Handle<v8::Value> IDWeakMap::Remove(const v8::Arguments& args) {
if (!args[0]->IsNumber()) if (!args[0]->IsNumber())
@ -128,6 +143,7 @@ void IDWeakMap::Initialize(v8::Handle<v8::Object> target) {
NODE_SET_PROTOTYPE_METHOD(t, "add", Add); NODE_SET_PROTOTYPE_METHOD(t, "add", Add);
NODE_SET_PROTOTYPE_METHOD(t, "get", Get); NODE_SET_PROTOTYPE_METHOD(t, "get", Get);
NODE_SET_PROTOTYPE_METHOD(t, "has", Has); NODE_SET_PROTOTYPE_METHOD(t, "has", Has);
NODE_SET_PROTOTYPE_METHOD(t, "keys", Keys);
NODE_SET_PROTOTYPE_METHOD(t, "remove", Remove); NODE_SET_PROTOTYPE_METHOD(t, "remove", Remove);
target->Set(v8::String::NewSymbol("IDWeakMap"), t->GetFunction()); target->Set(v8::String::NewSymbol("IDWeakMap"), t->GetFunction());

View file

@ -35,9 +35,10 @@ class IDWeakMap : public node::ObjectWrap {
static v8::Handle<v8::Value> Add(const v8::Arguments& args); static v8::Handle<v8::Value> Add(const v8::Arguments& args);
static v8::Handle<v8::Value> Get(const v8::Arguments& args); static v8::Handle<v8::Value> Get(const v8::Arguments& args);
static v8::Handle<v8::Value> Has(const v8::Arguments& args); static v8::Handle<v8::Value> Has(const v8::Arguments& args);
static v8::Handle<v8::Value> Keys(const v8::Arguments& args);
static v8::Handle<v8::Value> Remove(const v8::Arguments& args); static v8::Handle<v8::Value> Remove(const v8::Arguments& args);
int nextId_; int next_id_;
std::map<int, v8::Persistent<v8::Value>> map_; std::map<int, v8::Persistent<v8::Value>> map_;