需要减少双队列代码 [英] Double-Queue Code needs to be reduced
问题描述
有什么方法可以减少这个代码来做同样的事情,但是减去100个字符?
Is there any way I can reduce this code to do the same thing but with 100 less characters?
这是一个简单的双边缘队列,有pushHead,popHead, pushTail,popTail,以及访问长度和isEmpty的方法。
It's a simple double edge queue that has pushHead,popHead,pushTail,popTail, as well as a way to access the length and 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;
};
谢谢!
推荐答案
你可以摆脱手动数组处理。我猜你不能比这更短(你可以缩短变量名,但代码可能需要至少这么长)。
You could get rid of the manual array handling. I guess you can't get any shorter than this (you could shorten variable names, but the code probably needs to be at least this long).
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}
这样,您还可以获得默认数组的所有功能
以及。此示例中的 Deque
实际上是 Array
类的子类。
This way, you also get all the functionality of the default Arrays
as well. Deque
in this example effectively a sub-class of the Array
class.
这篇关于需要减少双队列代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!