常用 JavaScript 数据 - 列表


class List{
    constructor() {
        this.listSize = 0
        this.pos = 0;
        this.dataStore = [];
    }
    clear() { 
        delete this.dataStore
        this.dataStore = []
        this.listSize = this.pos = 0
    }
    insert(el, after) {
        const insPos = this.__find(after)
        if (insPos > -1) {
            this.dataStore.splice(insPos + 1, 0, el)
            ++this.listSize
            return true
        }
        return false
    }
    add(el) { 
        if(this.dataStore.every(item => {
           return el>item
        })) {
            this.append(el)
        }
    }
    lessAdd(el) {
        if(this.dataStore.every(item => {
           return el<item
        })) {
            this.append(el)
        }        
    }
    contains(el) { 
        return this.__find(el)>-1
    }
    // 追加元素
    append(el) {
        this.dataStore[this.listSize++] = el
    }
    __find(el) {
        return this.dataStore.findIndex(item=>item===el)
     }
    remove(el) {
        const idx = this.__find(el)
        if (idx > -1) {
            this.dataStore.splice(idx, 1)
            --this.listSize;
            return true
        }
        return false;
    }
    length() {
        return this.listSize
    }
    front() {
        this.pos=0
    }
    end() {
        this.pos = this.listSize-1
    }
    prev() {
        if (this.pos > 0) {
            --this.pos
        }
    }
    next() {
        this.pos < this.listSize ? ++this.pos : this.pos
    }
    currPos() {
        return this.pos
    }
    moveTo(pos) {
        this.pos = pos
    }
    toString() { 
        return this.dataStore.toString()
    }
    getElement() { 
        return this.dataStore[this.pos]
    }
}
百度未收录
分享