Shortly before the interview, I met a question like, " write a cache function that looks up records based on the ID field, and if checked before, returns the object that was previously looked up without having to look for it again ." Due to the short time and time is more tense, the consideration is not particularly full, and did not write a more appropriate method (not popular call). Today I think about it, made some improvements, hope that we give more guidance. The idea is to use closures and arrays of the Find method.
var getitem=function () {var cachearr=[]; Determines whether the array supports the Find method, and if not supported, expands 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==un Defined) {var newitem=arr.find (the 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);}
Test objects and how to use them:
varscorestable=[{ID:11,name: "Xiao Zhang", score:80}, {ID:22,name: "Xiao Wang", score:95}, {ID:33,name: "Xiao Li", score:50}, {ID:44,name: "Xiao Liu", score:65}, {ID:55,name: "Xiao Xu", score:84}]//module initialization usingConsole.log (Scorestable.getitembyid (11)) Console.log (GetItemByID (11, scorestable));//module initialization usingConsole.log (Scorestable.getitembyid (22)); Console.log (GetItemByID (11, scorestable)); Console.log (GetItemByID (22, scorestable)); Console.log (GetItemByID (11,scorestable));
The results of the implementation are as follows:
Write a cache function (JavaScript) that looks up records based on the ID field