| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
#include "../quickjs.h" |
| 25 |
|
| 26 |
#define countof(x) (sizeof(x) / sizeof((x)[0])) |
| 27 |
|
| 28 |
static int fib(int n) |
| 29 |
{ |
| 30 |
if (n <= 0) |
| 31 |
return 0; |
| 32 |
else if (n == 1) |
| 33 |
return 1; |
| 34 |
else |
| 35 |
return fib(n - 1) + fib(n - 2); |
| 36 |
} |
| 37 |
|
| 38 |
static JSValue js_fib(JSContext *ctx, JSValueConst this_val, |
| 39 |
int argc, JSValueConst *argv) |
| 40 |
{ |
| 41 |
int n, res; |
| 42 |
if (JS_ToInt32(ctx, &n, argv[0])) |
| 43 |
return JS_EXCEPTION; |
| 44 |
res = fib(n); |
| 45 |
return JS_NewInt32(ctx, res); |
| 46 |
} |
| 47 |
|
| 48 |
static const JSCFunctionListEntry js_fib_funcs[] = { |
| 49 |
JS_CFUNC_DEF("fib", 1, js_fib ), |
| 50 |
}; |
| 51 |
|
| 52 |
static int js_fib_init(JSContext *ctx, JSModuleDef *m) |
| 53 |
{ |
| 54 |
return JS_SetModuleExportList(ctx, m, js_fib_funcs, |
| 55 |
countof(js_fib_funcs)); |
| 56 |
} |
| 57 |
|
| 58 |
#ifdef JS_SHARED_LIBRARY |
| 59 |
#define JS_INIT_MODULE js_init_module |
| 60 |
#else |
| 61 |
#define JS_INIT_MODULE js_init_module_fib |
| 62 |
#endif |
| 63 |
|
| 64 |
JSModuleDef *JS_INIT_MODULE(JSContext *ctx, const char *module_name) |
| 65 |
{ |
| 66 |
JSModuleDef *m; |
| 67 |
m = JS_NewCModule(ctx, module_name, js_fib_init); |
| 68 |
if (!m) |
| 69 |
return NULL; |
| 70 |
JS_AddModuleExportList(ctx, m, js_fib_funcs, countof(js_fib_funcs)); |
| 71 |
return m; |
| 72 |
} |