需要减少双队列代码

时间:2013-08-30 11:24:43

标签: javascript

有什么方法可以减少这个代码来做同样的事情,但是减去100个字符?

这是一个简单的双边队列,有pushHead,popHead,pushTail,popTail,以及访问长度和isEmpty的方法。

var makeDeque = function()
{
    var a= [];
    this.length= a.length=0;

    this.pushHead=function(v)
    {
        a.unshift(v);
    }
    this.popHead=function()
    {
        return a.shift();
    }

    this.pushTail=function(v)
    {
        a.push(v);
    }

    this.popTail=function()
    {
    return a.pop();
    }

    this.isEmpty=function()
    {
        return a.length===0;
    }

    return this;
};

谢谢!

1 个答案:

答案 0 :(得分:0)

你可以摆脱手动数组处理。我猜你不能比这更短(你可以缩短变量名,但代码可能需要至少这么长)。

function Deque() {}
Deque.prototype = new Array();
var prot = Deque.prototype;
prot.pushHead = Deque.prototype.unshift;
prot.popHead = Deque.prototype.shift;
prot.pushTail = Deque.prototype.push
prot.popTail = Deque.prototype.pop
prot.isEmpty = function() {return this.length == 0}

这样,您还可以获得默认Arrays的所有功能。此示例中的Deque实际上是Array类的子类。

相关问题