Middle
Practical task: write a function that takes a number and returns a Promise with the result of checking for even/odd, and on error (not a number) returns -1.
sobes.tech AI
Answer from AI
A function that takes a number and returns a Promise with the result of checking for even/odd, and returns -1 on error, might look like this:
function checkParity(value: any): Promise<string | number> {
return new Promise((resolve) => {
if (typeof value !== 'number' || isNaN(value)) {
resolve(-1);
} else if (value % 2 === 0) {
resolve('even');
} else {
resolve('odd');
}
});
}
// Example usage:
checkParity(4).then(console.log); // "even"
checkParity(7).then(console.log); // "odd"
checkParity('abc').then(console.log); // -1
Here, we check the type and validity of the input value, and return the result in a Promise, which is convenient for asynchronous use.