git » jacl.git » commit e81bb61

Fix append

author Alan Dipert
2021-07-30 05:15:49 UTC
committer Alan Dipert
2021-07-30 05:15:49 UTC
parent 397c1fc4e66fe51647a45afabd07b43f136355b7

Fix append

jacl.js +16 -8

diff --git a/jacl.js b/jacl.js
index 39242ce..6e2150d 100644
--- a/jacl.js
+++ b/jacl.js
@@ -54,6 +54,14 @@ class List {
       throw new Error(`Unsupported type`);
     }
   }
+  static nthcdr(x, n) {
+    if (x === null) return null;
+    if (x instanceof Cons) {
+      return n === 0 ? x : List.nthcdr(x.cdr, n-1);
+    } else {
+      throw new Error(`Unsupported type`);
+    }
+  }
   static isProperList(x) {
     if (x === null) return true;
     if (x instanceof Cons) return List.isProperList(x.cdr);
@@ -130,16 +138,16 @@ class Cons {
       return null;
     } else if (xs.length === 1) {
       return xs[0];
-    } else if (xs.length === 2 && !(xs[1] instanceof Cons)) {
-      const copy = Cons.listOf(...xs[0]);
-      let last = copy;
-      while (last.cdr) last = last.cdr;
-      last.cdr = xs[1];
-      return copy;
     } else if (xs.length === 2) {
-      return Cons.listOf(...xs[0], ...xs[1]);
+      if (xs[0] === null) return xs[1];
+      let arr = [...List.toArray(xs[0])],
+          ret = Cons.fromArray(arr),
+          lastcons = List.nthcdr(ret, arr.length-1);
+      lastcons.cdr = xs[1];
+      return ret;
     } else {
-      return xs.reduce((a, b) => Cons.append(a,b));
+      let ret = Cons.fromArray(xs.slice(0, xs.length-1).flatMap(x => List.toArray(x)));
+      return Cons.append(ret, xs[xs.length-1]);
     }
   }
   static toArray(cons) {