Skip to content

Commit

Permalink
Introduce IterateArray utility
Browse files Browse the repository at this point in the history
  • Loading branch information
zcbenz committed Jul 18, 2024
1 parent 8be1b76 commit 8d67386
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 31 deletions.
30 changes: 30 additions & 0 deletions src/iterator.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#ifndef SRC_ITERATOR_H_
#define SRC_ITERATOR_H_

#include "src/types.h"

namespace ki {

template<typename T>
bool IterateArray(napi_env env, napi_value arr,
const std::function<void(uint32_t i, T value)>& visit) {
if (!IsArray(env, arr))
return false;
uint32_t length;
if (napi_get_array_length(env, arr, &length) != napi_ok)
return false;
for (uint32_t i = 0; i < length; ++i) {
napi_value el = nullptr;
if (napi_get_element(env, arr, i, &el) != napi_ok)
return false;
std::optional<T> out = FromNodeTo<T>(env, el);
if (!out)
return false;
visit(i, *out);
}
return true;
}

} // namespace ki

#endif // SRC_ITERATOR_H_
40 changes: 9 additions & 31 deletions src/std_types.h
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#ifndef SRC_STD_TYPES_H_
#define SRC_STD_TYPES_H_

#include "src/types.h"
#include "src/iterator.h"

#include <set>
#include <string>
Expand Down Expand Up @@ -81,23 +81,12 @@ struct Type<std::vector<T>> {
}
static std::optional<std::vector<T>> FromNode(napi_env env,
napi_value value) {
if (!IsArray(env, value))
return std::nullopt;
uint32_t length;
if (napi_get_array_length(env, value, &length) != napi_ok)
std::vector<T> r;
if (!IterateArray<T>(env, value,
[&](uint32_t i, T v) { r.push_back(std::move(v)); })) {
return std::nullopt;
std::vector<T> result;
result.reserve(length);
for (uint32_t i = 0; i < length; ++i) {
napi_value el = nullptr;
if (napi_get_element(env, value, i, &el) != napi_ok)
return std::nullopt;
std::optional<T> out = FromNodeTo<T>(env, el);
if (!out)
return std::nullopt;
result.push_back(std::move(*out));
}
return result;
return r;
}
};

Expand All @@ -121,23 +110,12 @@ struct Type<std::set<T>> {
}
static std::optional<std::set<T>> FromNode(napi_env env,
napi_value value) {
if (!IsArray(env, value))
std::set<T> r;
if (!IterateArray<T>(env, value,
[&](uint32_t i, T v) { r.insert(std::move(v)); })) {
return std::nullopt;
uint32_t length;
if (napi_get_array_length(env, value, &length) != napi_ok)
return std::nullopt;
std::set<T> result;
result.reserve(length);
for (uint32_t i = 0; i < length; ++i) {
napi_value el;
if (napi_get_element(env, value, i, &el) != napi_ok)
return std::nullopt;
std::optional<T> element = FromNodeTo<T>(env, el);
if (!element)
return std::nullopt;
result.insert(std::move(*element));
}
return result;
return r;
}
};

Expand Down

0 comments on commit 8d67386

Please sign in to comment.