Last active
October 19, 2021 13:01
-
-
Save AhmedTarekHasan/173b55c5d749bea47f7d1637fc4feda6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let Subject = function(subscribersStateChangeNotificationCallback) { | |
let self = this; | |
let handlers = {}; | |
Object.defineProperty(self, "subscribersFound", { | |
get() { | |
let found = false; | |
for(const prop in handlers) { | |
if(handlers.hasOwnProperty(prop)) { | |
found = true; | |
break; | |
} | |
} | |
return found; | |
} | |
}); | |
Object.defineProperty(self, "subscribersCount", { | |
get() { | |
let count = 0; | |
for(const prop in handlers) { | |
if(handlers.hasOwnProperty(prop)) { | |
count++; | |
} | |
} | |
return count; | |
} | |
}); | |
let unsubscribeNotificationCallback = (handlerId) => { | |
if(handlerId && handlerId !== '' && handlers.hasOwnProperty(handlerId)) { | |
delete handlers[handlerId]; | |
if(subscribersStateChangeNotificationCallback && !self.subscribersFound) { | |
subscribersStateChangeNotificationCallback(false); | |
} | |
} | |
}; | |
self.subscribe = (handler) => { | |
let handlerId = createGuid(); | |
handlers[handlerId] = handler; | |
if(subscribersStateChangeNotificationCallback && self.subscribersCount === 1) { | |
subscribersStateChangeNotificationCallback(true); | |
} | |
return new Subscription(handlerId, unsubscribeNotificationCallback); | |
}; | |
self.next = (data) => { | |
for(const handlerId in handlers) { | |
handlers[handlerId](data); | |
} | |
}; | |
return self; | |
}; | |
let createGuid = function() { | |
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { | |
var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8); | |
return v.toString(16); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment