From 6f8f6a9827d3eb715bc93c97879132c4bbd4cacc Mon Sep 17 00:00:00 2001 From: evilrescuer Date: Tue, 26 Mar 2019 23:20:00 +1100 Subject: [PATCH] pass test --- Observable.js | 16 ++++++++++------ PubSub.js | 10 +++++++--- 2 files changed, 17 insertions(+), 9 deletions(-) diff --git a/Observable.js b/Observable.js index 03545cd..db4bd8c 100644 --- a/Observable.js +++ b/Observable.js @@ -10,13 +10,17 @@ class ObserverList { this.observerList = []; } add(observer) { - // todo add observer to list + this.observerList.push(observer) } remove(observer) { - // todo remove observer from list + this.observerList = + this.observerList.filter(item => item !== observer) } count() { - // return observer list size + return this.observerList.length + } + publish(...args) { + this.observerList.forEach(item => item.update(...args)) } } @@ -25,13 +29,13 @@ class Subject { this.observers = new ObserverList(); } addObserver(observer) { - // todo add observer + this.observers.add(observer) } removeObserver(observer) { - // todo remove observer + this.observers.remove(observer) } notify(...args) { - // todo notify + this.observers.publish(...args) } } diff --git a/PubSub.js b/PubSub.js index 0c7999e..0dc34b2 100644 --- a/PubSub.js +++ b/PubSub.js @@ -12,15 +12,19 @@ module.exports = class PubSub { } subscribe(type, fn) { - // todo subscribe + this.subscribers[type] ? + this.subscribers[type].push(fn): + this.subscribers[type] = [fn] } unsubscribe(type, fn) { - // todo unsubscribe + this.subscribers[type] = + (this.subscribers[type] || []) + .filter(item => item !== fn) } publish(type, ...args) { - // todo publish + (this.subscribers[type] || []).forEach(item => item(...args)) } }