Last active
April 17, 2020 16:30
-
-
Save bengfarrell/4440739 to your computer and use it in GitHub Desktop.
Random Coordinates C++ Node.JS AddOn
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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