Iterator模式参考图片:
代码:
var Iterator = function() {};
Iterator.prototype.first = function(){};
Iterator.prototype.next = function(){};
Iterator.prototype.isDone = function(){};
Iterator.prototype.currentItem = function(){};
var ArrayIterator = function(o) {
var items = o;
var curIdx = -1;
this.first = function() {
if (items == null || items.length < 1)
return null;
curIdx = 0;
return items[0];
};
this.next = function() {
if (items == null || items.length < 1)
return null;
if (this.isDone())
return items[items.length - 1];
else
return items[curIdx++];
};
this.isDone = function() {
if (items == null || items.length < 1 || items[curIdx] == null)
return true;
else
return false;
};
this.currentItem = function() {
if (this.isDone())
return null;
else
return items[curIdx];
};
this.currentIdx = function() {
return curIdx;
};
};
ArrayIterator.prototype = new Iterator;
ArrayIterator.prototype.constructor = ArrayIterator;
var Map = function() {};
Map.prototype.createIterator = function() {};
var MyMap = function() {
this.datas = new Array;
this.createIterator = function() {
return new ArrayIterator(this.datas);
};
};
MyMap.prototype = new Map;
MyMap.prototype.constructor = MyMap;
MyMap.prototype.find = function(key) {
var itor = this.createIterator();
itor.first();
var item;
while(!itor.isDone()) {
item = itor.currentItem();
if (key.localeCompare(item.key) == 0)
return item.value;
itor.next();
};
return null;
};
MyMap.prototype.update = function(key, value) {
var itor = this.createIterator();
itor.first();
var item;
while(!itor.isDone()) {
item = itor.currentItem();
if (key.localeCompare(item.key) == 0) {
this.datas.splice(itor.currentIdx(), 1, {key:key, value:value});
return true;
}
itor.next();
};
return false;
};
MyMap.prototype.add = function(key, value, ifUpdate) {
var item = this.find(key);
if (item != null && ifUpdate == true)
return this.update(key, value);
if (item == null) {
this.datas.push({key:key, value:value});
return true;
}
return false;
};
MyMap.prototype.del = function(key) {
var itor = this.createIterator();
itor.first();
var item;
while(!itor.isDone()) {
item = itor.currentItem();
if (key.localeCompare(item.key) == 0) {
this.datas.splice(itor.currentIdx(), 1);
return item;
}
itor.next();
};
return null;
};
var o = new MyMap;
o.add("1", {a:1});
o.add("2", {a:2});
o.add("3", {a:3, b:33});
o.add("3", {a:3, b:333}, true);
o.add("3", {a:3, b:33333});
o.add("4", {a:4, c:44});
o.add("5", {a:5});
console.log(o.find("3"));
o.del("3");
console.log(o.find("3"));

本文介绍了一种使用JavaScript实现迭代器模式的方法,通过自定义ArrayIterator类来遍历数组,并结合MyMap类实现了键值对的查找、更新、添加及删除等操作。
9326

被折叠的 条评论
为什么被折叠?



