2013-08-30 51 views
0

有沒有什麼辦法可以減少這段代碼來做同樣的事情,但減少100個字符?需要減少雙隊列代碼

這是一個簡單的雙邊隊列,它具有pushHead,popHead,pushTail,popTail,以及訪問length和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; 
}; 

謝謝!

+0

看看http://stackoverflow.com/questions/18544265/pointers-and-array-class-in-javascript/18544420#18544420 – plalx

回答

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類的一個子類。