I'm trying to create a Node.js C++ Addon that generates the Fibonacci sequence to compare its speed with a normal Node.js module, but I'm having trouble setting a certain index of an array. I've got this so far:
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Value;
using v8::Number;
using v8::Array;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
Local<Array> arr = Array::New(isolate, n);
for (; c < n; c++) {
if ( c <= 1 ) next = c;
else {
next = first + second;
first = second;
second = next;
}
// How to set arr[c]?????
}
args.GetReturnValue().Set(arr);
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "fib", Method);
}
NODE_MODULE(addon, init)
}
On line 26, how should I set arr[c]
? v8:Array
doesn't provide a subscript operator.
how should I set arr[c]? v8:Array doesn't provide a subscript operator.
It doesn't, but v8::Array
already inherits the function member Set
from v8::Object
, with an overload that takes an integer (uint32_t
) for the key. Use it to populate each element of the array:
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
int next, first = 0, second = 0, c = 0, n = args[0]->NumberValue();
Local<Array> arr = Array::New(isolate, n);
int i = 0;
for (; c < n; c++) {
if ( c <= 1 ) next = c;
else {
next = first + second;
first = second;
second = next;
}
arr->Set(i++, Number::New(isolate, next));
}
args.GetReturnValue().Set(arr);
}