Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jcharles22/c4fbe2c2c78062c7db85553c8bbc5b56 to your computer and use it in GitHub Desktop.
Save jcharles22/c4fbe2c2c78062c7db85553c8bbc5b56 to your computer and use it in GitHub Desktop.
Web APIs with Express Drills
//Drill 1
app.get('/sum', (req, res) => {
const a = parseInt(req.query.a);
const b = parseInt(req.query.b);
if(!a || !b) {
res.send('Please send 2 numbers');
} else {
res.send(`The sum of ${a} and ${b} is ${a+b}`)
}
})
//Drill 2
app.get('/cipher', (req, res) => {
const text = req.query.text;
const shift = parseInt(req.query.shift);
if(text==='' || !text) {
res.status(400).send('Please enter a String')
}
if(!parseInt(shift)) {
res.status(400).send('Please enter a number')
}
const shifted = text.toUpperCase().split('').map(letter => {
if(letter.charCodeAt(0)+shift>91) {
return String.fromCharCode(65+(letter.charCodeAt(0)+shift-91))
}
else{
return String.fromCharCode(letter.charCodeAt(0)+shift)
}
})
res.send(shifted);
})
//Drill 3
app.get('/loto', (req, res) => {
const {numbers} = req.query
const guess = numbers.map((index) => parseInt(index))
const randomNumbers = []
for(let i = 0; i<6; i++){
if(!numbers[i]) {
res.send('Please enter 6 numbers');
}
if(numbers[i] > 20 || numbers[i] < 0){
res.send('Please pick numbers between 1 and 20')
} else{
randomNumbers.push(Math.floor((Math.random() * 20) + 1));
}
}
let check = randomNumbers.filter((num) => !guess.includes(num))
// console.log(guess, randomNumbers, check)
let responseText;
switch(check.length){
case 0:
responseText = 'Wow! Unbelievable! You could have won the mega millions!';
break;
case 1:
responseText = 'Congratulations! You win $100!';
break;
case 2:
responseText = 'Congratulations, you win a free ticket!';
break;
default:
responseText = 'Sorry, you lose';
}
res.send(responseText);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment