about summary refs log tree commit diff stats
path: root/qjs
diff options
context:
space:
mode:
authoreli-oat <hi@eli.li>2022-10-02 15:35:05 -0400
committereli-oat <hi@eli.li>2022-10-02 15:35:05 -0400
commit4d8e1a29b7eb58e2ee6de2289a67397594873adb (patch)
tree2a2aba8f01712b3b7b159afef62140a0dcb15846 /qjs
parentab5d5539591634d30fbd0f7e9a498f44703c9036 (diff)
downloadtour-4d8e1a29b7eb58e2ee6de2289a67397594873adb.tar.gz
*
Diffstat (limited to 'qjs')
-rw-r--r--qjs/README13
-rw-r--r--qjs/fact.js38
-rw-r--r--qjs/utils.js7
3 files changed, 58 insertions, 0 deletions
diff --git a/qjs/README b/qjs/README
new file mode 100644
index 0000000..e75930a
--- /dev/null
+++ b/qjs/README
@@ -0,0 +1,13 @@
+# quickjs
+
+Run, 
+
+```
+qjs fact.js
+```
+
+Or compile, 
+
+```
+qjsc -o fact fact.js
+```
\ No newline at end of file
diff --git a/qjs/fact.js b/qjs/fact.js
new file mode 100644
index 0000000..c5d718e
--- /dev/null
+++ b/qjs/fact.js
@@ -0,0 +1,38 @@
+import {assert} from "utils.js";
+
+
+// https://sourceacademy.org/sicpjs/1.2.1#fig-1.6
+// recursive 
+function factorial_01(n) {
+    return n === 1 
+           ? 1
+           : n * factorial_01(n - 1);
+} 
+assert(factorial_01(7) === 5040, 'factorial_01 returns an incorrect result.')
+console.log(factorial_01(7), 'v01')
+
+
+// https://sourceacademy.org/sicpjs/1.2.1#fig-1.8 
+// iterative
+function factorial_02(n) {
+    return fact_iter(1, 1, n);
+}
+function fact_iter(product, counter, max_count) {
+    return counter > max_count
+           ? product
+           : fact_iter(counter * product,
+                       counter + 1,
+                       max_count);
+}
+assert(factorial_02(7) === 5040, 'factorial_02 returns an incorrect result.')
+console.log(factorial_02(7), 'v02')
+
+
+// FROM SICP
+// In contrasting iteration and recursion, we must be careful not to confuse the 
+// notion of a recursive process with the notion of a recursive function. When we 
+// describe a function as recursive, we are referring to the syntactic fact that 
+// the function declaration refers (either directly or indirectly) to the function 
+// itself. But when we describe a process as following a pattern that is, say, 
+// linearly recursive, we are speaking about how the process evolves, not about 
+// the syntax of how a function is written.
\ No newline at end of file
diff --git a/qjs/utils.js b/qjs/utils.js
new file mode 100644
index 0000000..eaae753
--- /dev/null
+++ b/qjs/utils.js
@@ -0,0 +1,7 @@
+
+// wicked simple testing in place of console.assert
+export function assert(condition, message) {
+    if (!condition) {
+        throw new Error(message || 'Assertion failed');
+    }
+}
\ No newline at end of file