function Stream() {
let subscriber = new Map();
return {
subscribe: function(method) {
if(typeof method === 'function') {
subscriber.set(method);
}
else
throw new Error('Pass a valid method.');
},
push: function(val) {
[...subscriber].forEach(([method]) => method(val));
},
unsubscribe: function(method) {
console.log(subscriber.has([method]));
console.log([method]);
[...subscriber].forEach(([method]) => console.log([method]));
if (typeof method === 'function' && subscriber){
subscriber.delete([method]);
}
[...subscriber].forEach(([method]) => console.log([method]));
}
};
}
var stream = new Stream();
stream.subscribe((val)=>console.log(val*1));
stream.subscribe((val)=>console.log(val*2));
stream.subscribe((val)=>console.log(val*3));
stream.push(2);
stream.push(3);
stream.unsubscribe((val)=>console.log(val*3));
stream.push(4);
In the unsubscibe function, which shows up that "subscriber.has([method]) " returns false to me, but after I print the method out and compare with in side of the subscriber map, which looks the same. Is there anything wrong here?
[method]creates a new array (with one element) each time, so it's never in the map..set().stream.unsubscribe((val)=>console.log(val*3))will never match anything anyway. Two arrow functions, even if equivalent logic, will never be the same.