|
| 1 | +#include <node/v8.h> |
| 2 | +#include <node/node.h> |
| 3 | + |
| 4 | +using namespace v8; |
| 5 | + |
| 6 | +// Returns the Nth number in the fibonacci sequence where N is the first |
| 7 | +// argument passed. |
| 8 | +Handle<Value> Fibonacci(const Arguments& args) { |
| 9 | + HandleScope scope; |
| 10 | + |
| 11 | + // Check that there are enough arguments. If we access an index that doesn't |
| 12 | + // exist, it'll be Undefined(). |
| 13 | + if (args.Length() < 1) { |
| 14 | + // No argument was passed. Throw an exception to alert the user to |
| 15 | + // incorrect usage. Alternatively, we could just use 0. |
| 16 | + return ThrowException( |
| 17 | + Exception::TypeError(String::New("First argument must be a number")) |
| 18 | + ); |
| 19 | + } |
| 20 | + |
| 21 | + // Cast a value to a specific type. See |
| 22 | + // http://izs.me/v8-docs/classv8_1_1Value.html for available To*() functions |
| 23 | + // and type checking functions. When converting to integer, make sure the |
| 24 | + // POD type you use is big enough! |
| 25 | + Local<Integer> integer = args[0]->ToInteger(); |
| 26 | + int32_t seq = integer->Value(); |
| 27 | + |
| 28 | + // Also possible in one call. (Don't forget HandleScope, otherwise the |
| 29 | + // intermediate Local handle won't be cleaned up!) |
| 30 | + // int32_t seq = args[0]->ToInteger()->Value(); |
| 31 | + |
| 32 | + // Check for invalid parameter. |
| 33 | + if (seq < 0) { |
| 34 | + return ThrowException(Exception::TypeError(String::New( |
| 35 | + "Fibonacci sequence number must be positive"))); |
| 36 | + } |
| 37 | + |
| 38 | + // The actual algorithm. |
| 39 | + int32_t current = 1; |
| 40 | + for (int32_t previous = -1, next = 0, i = 0; i <= seq; i++) { |
| 41 | + next = previous + current; |
| 42 | + previous = current; |
| 43 | + current = next; |
| 44 | + } |
| 45 | + |
| 46 | + return scope.Close(Integer::New(current)); |
| 47 | +} |
| 48 | + |
| 49 | +void RegisterModule(Handle<Object> target) { |
| 50 | + target->Set(String::NewSymbol("fibonacci"), |
| 51 | + FunctionTemplate::New(Fibonacci)->GetFunction()); |
| 52 | +} |
| 53 | + |
| 54 | +NODE_MODULE(modulename, RegisterModule); |
0 commit comments