-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsrc.cc
47 lines (40 loc) · 1015 Bytes
/
src.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <napi.h>
#include <math.h>
namespace primes {
bool isPrime(int p) {
int upper = sqrt(p);
for(int i = 2; i <= upper; i++) {
if (p % i == 0 ) {
return false;
}
}
return true;
}
// Return n-th prime
int prime(napi_env env, int n) {
if (n < 1) {
napi_throw_error(env, nullptr, "n too small");
}
int count = 0;
int result = 1;
while(count < n) {
result++;
if (isPrime(result)) {
count++;
}
}
return result;
}
Napi::Value Method(const Napi::CallbackInfo& info) {
Napi::Env env = info.Env();
int number = info[0].ToNumber().Int32Value();
int res = primes::prime(env, number);
return Napi::Number::New(env, res);
}
Napi::Object Init(Napi::Env env, Napi::Object exports) {
exports.Set(Napi::String::New(env, "prime"),
Napi::Function::New(env, Method));
return exports;
}
NODE_API_MODULE(NODE_GYP_MODULE_NAME, Init)
} // End namespace prime