前不久在參加面試的時候遇到了這樣一道題,"寫一個根據id字段查找記錄的緩存函數,若是以前查過,則直接返回以前查找過的對象,而無須從新查找"。當時因爲時間較短加上時間比較緊張,考慮並非特別全,並無寫出一個比較合適的方法(沒法普及調用)。今天回過頭想了一下,作了一些改進,望你們多給與指點。思路上採用閉包和數組的find方法。javascript
var getItem=function () { var cacheArr=[]; //判斷數組是否支持find方法,若是不支持則擴充 if (!Array.prototype.find) { Array.prototype.find = function(predicate) { if (this === null) { throw new TypeError('Array.prototype.find called on null or undefined'); } if (typeof predicate !== 'function') { throw new TypeError('predicate must be a function'); } var list = Object(this); var length = list.length >>> 0; var thisArg = arguments[1]; var value; for (var i = 0; i < length; i++) { value = list[i]; if (predicate.call(thisArg, value, i, list)) { return value; } } return undefined; }; } getItemById= function(id,arr){ var temp=cacheArr.find(function (item) {return item.id==id}) if(temp==undefined){ var newItem=arr.find(function (item) {return item.id==id}); cacheArr.push(newItem); console.log("New Data") return newItem; }else{ console.log("Cache Data") return temp; } }; return getItemById; } Array.prototype.getItemById=function(id){ return getItem().call([],id,this); }
測試對象及使用方法:java
var scoresTable=[ {id:11,name:"小張",score:80}, {id:22,name:"小王",score:95}, {id:33,name:"小李",score:50}, {id:44,name:"小劉",score:65}, {id:55,name:"小徐",score:84} ] //模塊初始化使用 console.log(scoresTable.getItemById(11)) console.log(getItemById(11,scoresTable)); //模塊初始化使用 console.log(scoresTable.getItemById(22)); console.log(getItemById(11,scoresTable)); console.log(getItemById(22,scoresTable)); console.log(getItemById(11,scoresTable));
執行結果以下:面試
方案二:利用new方法處理。數組
function Cache(arr){ this.cacheArr=[]; this.arr=arr; } Cache.prototype.byId=function(id){ var temp=this.cacheArr.find(function (item) {return item.id==id}) if(temp==undefined){ var newItem=this.arr.find(function (item) {return item.id==id}); this.cacheArr.push(newItem); console.log("New Data") return newItem; }else{ console.log("Cache Data") return temp; } }
測試對象及使用方法:緩存
var scoresTable=[ {id:11,name:"小張",score:80}, {id:22,name:"小王",score:95}, {id:33,name:"小李",score:50}, {id:44,name:"小劉",score:65}, {id:55,name:"小徐",score:84} ] var data=new Cache(scoresTable); console.log(data.byId(11)); console.log(data.byId(11)); console.log(data.byId(11)); console.log(data.byId(22)); console.log(data.byId(22));
執行結果以下:閉包