JavaScript
32K subscribers
1.03K photos
10 videos
33 files
714 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
CHALLENGE

class ValidationError extends Error {
constructor(message, code) {
super(message);
this.name = 'ValidationError';
this.code = code;
}
}

function processData(data) {
try {
if (!data) throw new ValidationError('Data required', 'MISSING_DATA');
return data.toUpperCase();
} catch (error) {
if (error instanceof ValidationError) {
console.log(`${error.name}: ${error.message} (${error.code})`);
} else {
console.log(`Unexpected error: ${error.message}`);
}
}
}

processData(null);
processData(42);
3
Please open Telegram to view this post
VIEW IN TELEGRAM
🤣40👍3🔥2
CHALLENGE

class StateMachine {
constructor() {
this.state = 'idle';
this.transitions = {
idle: { start: 'running', reset: 'idle' },
running: { pause: 'paused', stop: 'stopped' },
paused: { resume: 'running', stop: 'stopped' },
stopped: { reset: 'idle' }
};
}

transition(action) {
const nextState = this.transitions[this.state]?.[action];
if (nextState) {
this.state = nextState;
return true;
}
return false;
}
}

const sm = new StateMachine();
console.log(sm.transition('start'));
console.log(sm.state);
console.log(sm.transition('reset'));
console.log(sm.state);
5👍1🤔1
CHALLENGE

const target = { name: 'Sarah', age: 25 };
const handler = {
get(obj, prop) {
if (prop === 'toString') {
return () => `Person: ${obj.name}`;
}
return Reflect.get(obj, prop);
},
has(obj, prop) {
return prop !== 'age' && Reflect.has(obj, prop);
}
};
const proxy = new Proxy(target, handler);
console.log(proxy.name);
console.log('age' in proxy);
console.log(proxy.toString());