On JavaScript data structure (double ended queue)

Time:2020-11-26

A double ended queue is an ordered collection of items similar to a queue. In fact, it is a queue in essence. It is only a queue with both front-end and back-end supporting insert and delete operations, which is more practical. Therefore, there is no such statement as FIFO.

We can do this through arrays, but in order to write a more efficient data structure, we use objects.

class Deque{
    constructor(){
        this.count= 0;
        this.lowestCount = 0;
        this.items = {};
    }
    isEmptry(){
        return this.size() === 0;
    }
    size(){
        return this.count - this.lowestCount;
    }
    clear(){
        this.count= 0;
        this.lowestCount = 0;
        this.items = {};
    }
    toString(){
        if(this.isEmptry()){
            return '';
        }
        let objString = `${this.items[this.lowestCount]}`;
        for (let i=this.lowestCount+1;i<this.count;i++) {
            objString = `${objString},${this.items[i]}`;
        }
        return objString;
    }
    addBack(el){
        this.item[this.count]=el;
        this.count++;
    }
    addFront(el){
        if(this.isEmptry()){
            this.addBack(el);
        }else if(this.lowestCount>0){
            this.lowestCount--;
            this.item[this.lowestCount]=el;
        }else{
            for(let i=this.count;i>0;i--){
                this.item[i]=this.item[i-1];
            }
            this.count++;
            this.lowestCount=0;
            this.item[0]=el;
        }
    }
    removeFront(){
        if(this.isEmptry()){
            return undefined;
        }
        let c = this.items[this.lowestCount];
        delete this.items[this.lowestCount];
        this.lowestCount++;
        return c;
    }
    removeBack(){
         if (this.isEmpty()) {
            return undefined;
         }
         this.count--;
         let c = this.items[this.count];
         delete this.items[this.count];
         return c;
    }
    peekFront() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items[this.lowestCount];
    }
    peekBack() {
        if (this.isEmpty()) {
            return undefined;
        }
        return this.items[this.count - 1];
    }
 }

You can also use linked lists to implement this structure
Realization of linked list
This content can learn from JavaScript data structure and algorithm.

Recommended Today

The course of using Chinese software of poedit Pro

Poedit pro (formerly known as poedit) is a free (professional version charge), open source and cross platform gettext class (. Po format, gettext is used in the application program for program internationalization) International Translation editor. It is also one of the most widely used software of the same type. At present, it is available in […]