1 import assert from 'assert'
2 import LazyValue from './LazyValue.mjs'
4 class LazyArray extends LazyValue {
5 constructor(transaction, ptr_len, array) {
6 super(transaction, ptr_len)
7 this.array = array || []
8 this.length = this.array.length
12 assert(typeof key === 'number')
13 return key >= 0 && key < this.length
16 async get(key, default_value) {
17 assert(typeof key === 'number')
18 if (key < 0 || key >= this.length) {
19 if (default_value === undefined)
21 this.set(key, this.transaction.json_to_logjson(default_value))
24 let value = this.array[key]
25 if (value instanceof Array) {
26 value = await this.transaction.read(value)
27 this.array[key] = value
33 assert(typeof key === 'number')
35 typeof value !== 'object' ||
37 (value instanceof LazyValue && value.transaction === this.transaction)
39 this.ptr_len = null // mark dirty
40 this.array[key] = value
41 this.length = this.array.length
46 this.ptr_len = null // mark dirty
47 delete this.array[key]
51 splice(i, j, ...args) {
52 if (j || args.length) {
53 this.ptr_len = null // mark dirty
54 this.array.splice(i, j, ...args)
55 this.length = this.array.length
60 this.splice(0, 0, value)
64 this.unshift(this.transaction.json_to_logjson(value))
68 if (this.length === 0)
70 let value = await this.get(0)
71 await this.splice(0, 1)
76 return /*await*/ logjson.logjson_to_json(await this.shift())
80 this.splice(this.length, 0, value)
84 this.push(this.transaction.json_to_logjson(value))
88 if (this.length === 0)
90 let i = this.length - 1
91 let value = await this.get(i)
97 return /*await*/ logjson.logjson_to_json(await this.pop())
101 for (let i = 0; i < this.length; ++i) {
102 let value = this.array[i]
103 if (value instanceof LazyValue) {
104 if (await value.commit())
105 this.ptr_len = null // mark dirty
106 this.array[i] = value.ptr_len
110 if (this.ptr_len === null) {
111 this.ptr_len = await this.transaction.database.write(this.array)
118 export default LazyArray