all files / packages/list/ ListNode.js

92.59% Statements 25/27
50% Branches 3/6
100% Functions 12/12
100% Lines 25/25
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77          66×                   61× 61× 129×         45× 45× 45× 45×       67× 67×       65×       18× 18×                     25×                              
import { DocumentNode } from '../../model'
 
class ListNode extends DocumentNode {
 
  getItemAt(idx) {
    return this.getDocument().get(this.items[idx])
  }
 
  getFirstItem() {
    return this.getItemAt(0)
  }
 
  getLastItem() {
    return this.getItemAt(this.getLength()-1)
  }
 
  getItems() {
    const doc = this.getDocument()
    return this.items.map((id) => {
      return doc.get(id)
    })
  }
 
  getItemPosition(itemId) {
    Iif (itemId._isNode) itemId = itemId.id
    let pos = this.items.indexOf(itemId)
    Iif (pos < 0) throw new Error('Item is not within this list: ' + itemId)
    return pos
  }
 
  insertItemAt(pos, itemId) {
    const doc = this.getDocument()
    doc.update([this.id, 'items'], { type: 'insert', pos: pos, value: itemId })
  }
 
  appendItem(itemId) {
    this.insertItemAt(this.items.length, itemId)
  }
 
  removeItemAt(pos) {
    const doc = this.getDocument()
    doc.update([this.id, 'items'], { type: 'delete', pos: pos })
  }
 
  remove(itemId) {
    const doc = this.getDocument()
    const pos = this.getItemPosition(itemId)
    Eif (pos >= 0) {
      doc.update([this.id, 'items'], { type: 'delete', pos: pos })
    }
  }
 
  isEmpty() {
    return this.items.length === 0
  }
 
  getLength() {
    return this.items.length
  }
 
  get length() {
    return this.getLength()
  }
}
 
ListNode.isList = true
 
ListNode.type = 'list'
 
ListNode.schema = {
  ordered: { type: 'boolean', default: false },
  // list-items are owned by the list
  items: { type: [ 'array', 'id' ], default: [], owned: true }
}
 
export default ListNode