JavaScript
32K subscribers
1.04K photos
10 videos
33 files
717 links
A resourceful newsletter featuring the latest and most important news, articles, books and updates in the world of #javascript 🚀 Don't miss our Quizzes!

Let's chat: @nairihar
Download Telegram
Please open Telegram to view this post
VIEW IN TELEGRAM
🤣103👍1
CHALLENGE

class EventEmitter {
constructor() { this.events = {}; }
on(event, fn) { (this.events[event] ||= []).push(fn); }
emit(event, data) { this.events[event]?.forEach(fn => fn(data)); }
}

class Logger {
log(msg) { console.log(`LOG: ${msg}`); }
}

class Counter {
constructor() { this.count = 0; }
increment() { this.count++; console.log(this.count); }
}

function withLogging(target) {
const logger = new Logger();
return new Proxy(target, {
get(obj, prop) {
if (typeof obj[prop] === 'function') {
return function(...args) {
logger.log(`calling ${prop}`);
return obj[prop].apply(obj, args);
};
}
return obj[prop];
}
});
}

const emitter = withLogging(new EventEmitter());
const counter = new Counter();
emitter.on('tick', () => counter.increment());
emitter.emit('tick');
emitter.emit('tick');
🤔5
CHALLENGE

class Animal {
constructor(name) {
this.name = name;
}
speak() {
return `${this.name} makes a sound`;
}
}

class Dog extends Animal {
speak() {
return super.speak() + ' and barks';
}
}

const pet = new Dog('Rex');
console.log(pet.speak());
console.log(pet instanceof Animal);
console.log(pet.constructor.name);