Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions DesignPattern/19-迭代器模式.md
Original file line number Diff line number Diff line change
Expand Up @@ -552,3 +552,69 @@ func main() {
}
```

### Typescript

``` typescript
interface IIterator<T> {
hasNext(): boolean;
next(): T;
}

interface IIterable<T> {
createIterator(): IIterator<T>;
}

class NameList implements IIterator<string> {
private idx: number;
private nameList: string[];

constructor(names: string[]) {
this.nameList = names;
this.idx = 0;
}

hasNext(): boolean {
return this.idx < this.nameList.length;
}

next(): string {
if (this.hasNext()) {
return this.nameList[this.idx++];
} else {
throw "No more elements";
}
}
}

class ConcreteIterable implements IIterable<string> {
private ele: string[];

constructor(ele: string[]) {
this.ele = ele;
}

createIterator(): IIterator<string> {
return new NameList(this.ele);
}
}

// @ts-ignore
entry(3, (...args) => {
const iterator = new ConcreteIterable(args).createIterator();
while (iterator.hasNext()) {
console.log(iterator.next());
}
})("Alice 1001")("Bob 1002")("Charlie 1003");

function entry(count: number, fn: (...args: any) => void) {
function dfs(...args) {
if (args.length < count) {
return (arg) => dfs(...args, arg);
}

return fn(...args);
}
return dfs;
}
```