大厂前端面试题

实现一个类,语法可以是es5 / es6 / es7

调用代码可以输出:item1-1 item2-2 item3-3

调用代码如下:

var priorityQueue = new PriorityQueue();
priorityQueue.add('item1', 1);
priorityQueue.add('item3', 3);
priorityQueue.add('item2', 2);
priorityQueue.print();
priorityQueue.clear();

clipboard.png

阅读 2.5k
4 个回答

抛砖引玉 (ES5)

function PriorityQueue() {
    return {
        _data: "",
        add: function(label, value) {
            console.log("添加数据 " + label + "-" + value + " 成功");
            this._data += " " + label + "-" + value;
        },
        print: function() {
            console.log(this._data.slice(1));
            return this._data.slice(1);
        },
        clear: function() {
            console.log("数据已清除");
            this._data = "";
        }
    };
}
function PriorityQueue() {
    this._queues = {}; // 优先级为键,值为items数组
}

PriorityQueue.prototype.add = function(item, priority) {
    this._queues[priority] = this._queues[priority] || [];
    this._queues[priority].push(item);
}

PriorityQueue.prototype.print = function() {
    Object.keys(this._queues).sort().forEach(priority => {
        this._queues[priority].forEach(item => console.log(item));
    });
}

PriorityQueue.prototype.clear = function() {
    this._queues = {};
}

补充es6

class PriorityQueue {
    constructor() {
        this.data = []
        this.str = ""
    }
    add(label, value) {
        this.data.push({ 'label': label, 'value': value})
    }
    print() {
        this.data.sort((a,b) => a.value-b.value)
        this.data.forEach(item=>this.str += item.label+'_'+item.value+' ')
        console.log(this.str);//item1_1 item2_2 item3_3 
    }
    clear() {
        this.data = [];
        this.str = ""
    }
}

直接使用数组来保存数据,感觉可以更加简单一些。

class PriorityQueue {
    constructor() {
        this.data = [];
    }
    add(value, index) {
        this.data[index] = value;
    }
    print() {
        let array = [];
        this.data.forEach((item, index) => array.push(`${item}-${index}`));
        console.info(array.join(" "));
    }
    clear() {
        this.data = [];
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题