Implement LazyArray.splice(), implement unshift/shift/push/pop in terms of splice... master
authorNick Downing <nick@ndcode.org>
Sun, 13 Feb 2022 01:09:22 +0000 (12:09 +1100)
committerNick Downing <nick@ndcode.org>
Sun, 13 Feb 2022 01:09:22 +0000 (12:09 +1100)
LazyArray.mjs
Mutex.mjs

index 53b69fc..e174ab3 100644 (file)
@@ -48,18 +48,55 @@ class LazyArray extends LazyValue {
     }
   }
 
+  splice(i, j, ...args) {
+    if (j || args.length) {
+      this.ptr_len = null // mark dirty
+      this.array.splice(i, j, ...args)
+      this.length = this.array.length
+    }
+  }
+
+  unshift(value) {
+    this.splice(0, 0, value)
+  }
+
+  unshift_json(value) {
+    this.unshift(this.transaction.json_to_logjson(value))
+  }
+
+  async shift() {
+    if (this.length === 0)
+      return undefined
+    let value = await this.get(0)
+    await this.splice(0, 1)
+    return value
+  }
+
+  async shift_json() {
+    return /*await*/ logjson.logjson_to_json(await this.shift())
+  }
+
   push(value) {
-    this.set(this.length, value)
+    this.splice(this.length, 0, value)
+  }
+
+  push_json(value) {
+    this.push(this.transaction.json_to_logjson(value))
   }
 
   async pop() {
-    assert(this.length)
-    this.length -= 1
-    let value = await this.get(this.length)
-    this.delete(this.length)
+    if (this.length === 0)
+      return undefined
+    let i = this.length - 1
+    let value = await this.get(i)
+    this.splice(i, 1)
     return value
   }
 
+  async pop_json() {
+    return /*await*/ logjson.logjson_to_json(await this.pop())
+  }
+
   async commit() {
     for (let i = 0; i < this.length; ++i) {
       let value = this.array[i]
index 593245f..9398a6a 100644 (file)
--- a/Mutex.mjs
+++ b/Mutex.mjs
@@ -2,24 +2,24 @@ import assert from 'assert'
 
 class Mutex {
   constructor() {
-    this.done = null
+    this.ready = null
   }
 
   async acquire() {
-    while (this.done !== null)
-      await this.done.promise
-    let done = {}
-    done.promise = new Promise(
-      (resolve, reject) => {done.resolve = resolve}
+    while (this.ready !== null)
+      await this.ready.promise
+    let ready = {}
+    ready.promise = new Promise(
+      (resolve, reject) => {ready.resolve = resolve}
     )
-    this.done = done
+    this.ready = ready
   }
 
   release() {
-    let done = this.done
-    assert(done !== null)
-    this.done = null
-    done.resolve()
+    let ready = this.ready
+    assert(ready !== null)
+    this.ready = null
+    ready.resolve()
   }
 }