From 6dd8fa644c56639c0837602c0170c768f9543000 Mon Sep 17 00:00:00 2001 From: caojunjie <1301239018@qq.com> Date: Mon, 21 Oct 2024 19:51:50 +0800 Subject: [PATCH] =?UTF-8?q?feat(typescript):=2019=20=E8=BF=AD=E4=BB=A3?= =?UTF-8?q?=E5=99=A8=E6=A8=A1=E5=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...43\345\231\250\346\250\241\345\274\217.md" | 66 +++++++++++++++++++ 1 file changed, 66 insertions(+) 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; +} +``` +