Advertisement
Guest User

Untitled

a guest
Aug 31st, 2015
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. #include <node.h>
  2.  
  3. using namespace v8;
  4.  
  5. int factorial(int n) {
  6. if (n == 0) return 1;
  7. else return n * factorial(n - 1);
  8. }
  9.  
  10. void Factorial(const FunctionCallbackInfo<Value>& args) {
  11. Isolate* isolate = Isolate::GetCurrent();
  12. HandleScope scope(isolate);
  13.  
  14. if (args.Length() != 2) {
  15. isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong number of arguments")));
  16. } else {
  17. if (!(args[0]->IsNumber() && args[1]->IsFunction())) {
  18. isolate->ThrowException(Exception::TypeError(String::NewFromUtf8(isolate, "Wrong arguments type")));
  19. } else {
  20. int result = factorial(args[0]->Int32Value());
  21.  
  22. Local<Function> callbackFunction = Local<Function>::Cast(args[1]);
  23. const unsigned argc = 1;
  24. Local<Value> argv[argc] = { Number::New(isolate, result) };
  25.  
  26. callbackFunction->Call(isolate->GetCurrentContext()->Global(), argc, argv);
  27. }
  28. }
  29. }
  30.  
  31. void Init(Handle<Object> exports) {
  32. NODE_SET_METHOD(exports, "factorial", Factorial);
  33. }
  34.  
  35. NODE_MODULE(Factorial, Init)
  36.  
  37. var factorialAddon = require('./addons/Factorial');
  38. factorialAddon.factorial(5, function (result) {
  39. console.log(result);
  40. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement