diff --git "a/DesignPattern/19-\350\277\255\344\273\243\345\231\250\346\250\241\345\274\217.md" "b/DesignPattern/19-\350\277\255\344\273\243\345\231\250\346\250\241\345\274\217.md" index f94dcd5..a72235c 100644 --- "a/DesignPattern/19-\350\277\255\344\273\243\345\231\250\346\250\241\345\274\217.md" +++ "b/DesignPattern/19-\350\277\255\344\273\243\345\231\250\346\250\241\345\274\217.md" @@ -552,3 +552,69 @@ func main() { } ``` +### Typescript + +``` typescript +interface IIterator { + hasNext(): boolean; + next(): T; +} + +interface IIterable { + createIterator(): IIterator; +} + +class NameList implements IIterator { + 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 { + private ele: string[]; + + constructor(ele: string[]) { + this.ele = ele; + } + + createIterator(): IIterator { + 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; +} +``` +