美文网首页
前端-定制化链表

前端-定制化链表

作者: 夫子有多高酱 | 来源:发表于2017-08-29 10:59 被阅读0次
import { ctrlbarStore } from '../store' // mobx data
/**
 * 双向链表
 */
class Node {
  constructor (key) {
    this.prev = null
    this.key = key
    this.element = {}
    this.next = null
  }

  clear () {
    this.value = {}
  }
  // append 添加元素到 element
  append (key, value) {
    this.element[key] = value
  }

  forEach (fn) {
    const keys = Object.keys(this.element)
    keys.forEach(k => {
      fn(k, this.element[k])
    })
  }
}

class DoublyLinkedList {
  constructor () {
    this.length = 0
    this.head = null
    this.tail = null
  }
  // append 添加元素到尾部
  append (key) {
    if (!key) throw new Error('key is required')
    const node = new Node(key)
    if (!this.head) {
      this.head = this.tail = node
    } else {
      let cur = this.head
      while (cur && cur.key <= key) {
        if (cur.next) {
          cur = cur.next
        } else {
          break
        }
      }
      if (cur.next) {
        node.next = cur.next
        node.prev = cur
        cur.next = node
        node.next.prev = node
      } else {
        this.tail = node
        node.prev = cur
        cur.next = node
      }
    }
    this.length += 1
    ctrlbarStore.canvasCount = this.length
  }

  getNode (key) {
    if (!key) return null
    let cur = this.head
    let node = null
    while (!!cur && !node) {
      if (cur.key === key) {
        node = cur
      } else {
        cur = cur.next
      }
    }
    return node
  }

  getIndexFromKey (key) {
    if (!key) return 0
    let cur = this.head
    let index = 0
    while (true) {
      index += 1
      if (cur.key === key) break
      if (!cur.next) {
        index = 0
        break
      }
      cur = cur.next
    }
    return index
  }

  removeNode (key) {
    if (!key) return null
    let cur = this.head
    let node = null
    while (!!cur && !node) {
      if (cur.key === key) {
        node = cur
      } else {
        cur = cur.next
      }
    }
    if (!node) return
    this.length -= 1
    node.prev.next = node.next
    if (!node.next) this.tail = node.prev
    if (this.head.key === node.key) this.head = null
  }
}
export { Node, DoublyLinkedList }
export const canvasStore = new DoublyLinkedList()

相关文章

网友评论

      本文标题:前端-定制化链表

      本文链接:https://www.haomeiwen.com/subject/dbhodxtx.html