Skip to content

Instantly share code, notes, and snippets.

@bengfarrell
Last active April 17, 2020 16:30
Show Gist options
  • Save bengfarrell/4440739 to your computer and use it in GitHub Desktop.
Save bengfarrell/4440739 to your computer and use it in GitHub Desktop.
Random Coordinates C++ Node.JS AddOn
#include <node.h>
#include <v8.h>
#include <stdio.h>
#include <stdlib.h>
using namespace v8;
Handle<Value> getRandomCoords2D(const Arguments& args) {
HandleScope scope;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
return scope.Close(Undefined());
}
Local<Object> obj = Object::New();
obj->Set(String::NewSymbol("x"), Number::New( 1 + (rand() % xBound->IntegerValue() )));
obj->Set(String::NewSymbol("y"), Number::New( 1 + (rand() % yBound->IntegerValue() )));
return scope.Close(obj);
}
Handle<Value> getRandomCoords3D(const Arguments& args) {
HandleScope scope;
if (args.Length() < 3) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsNumber() || !args[1]->IsNumber() || !args[2]->IsNumber()) {
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
return scope.Close(Undefined());
}
Local<Number> xBound = args[0]->ToNumber();
Local<Number> yBound = args[1]->ToNumber();
Local<Number> zBound = args[2]->ToNumber();
Local<Object> obj = Object::New();
obj->Set(String::NewSymbol("x"), Number::New( 1 + (rand() % xBound->IntegerValue() )));
obj->Set(String::NewSymbol("y"), Number::New( 1 + (rand() % yBound->IntegerValue() )));
obj->Set(String::NewSymbol("z"), Number::New( 1 + (rand() % zBound->IntegerValue() )));
return scope.Close(obj);
}
void init(Handle<Object> target) {
target->Set(String::NewSymbol("getRandomCoords3D"),
FunctionTemplate::New(getRandomCoords3D)->GetFunction());
target->Set(String::NewSymbol("getRandomCoords2D"),
FunctionTemplate::New(getRandomCoords2D)->GetFunction());
}
NODE_MODULE(randomcoords, init)
@Julie728
Copy link

Julie728 commented Jun 5, 2014

Good example, thanks for sharing!

@octalmage
Copy link

@vitawasalreadytaken
Copy link

Thanks for the useful article. Haven't tried to run this yet but it seems getRandomCoords2D is missing these lines:

Local<Number> xBound = args[0]->ToNumber();
Local<Number> yBound = args[1]->ToNumber();

In fact you can do fine with just the 3D function. Whenever you need 2D coordinates you just ignore the z axis. Cuts down on code duplication.

@felipebcs
Copy link

That's great! I'm still preparing myself for my first Node project, and I'll sure build some nasty addons to boost performance in some heavy calculations

@SamanShafigh
Copy link

Nice example

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment