Skip to content

Instantly share code, notes, and snippets.

@ripleyaffect
Created August 23, 2015 18:18
Show Gist options
  • Save ripleyaffect/05463286ba2488791437 to your computer and use it in GitHub Desktop.
Save ripleyaffect/05463286ba2488791437 to your computer and use it in GitHub Desktop.
Solution for Thinkful's Express routing course (https://projects.thinkful.com/express-routing-for-safe-travel-99/)
/*
Traveling app for Thinkful's Express routing course
To run:
```sh
npm init
npm install express
npm install node-emoji
node routing.js
```
*/
var express = require('express');
var emoji = require('node-emoji');
var travelMap = [
[" ", " ", " ", " ", " "],
["e", "g", " ", " ", "g"],
[" ", "g", " ", " ", " "],
[" ", " ", " ", "s", " "],
[" ", " ", "g", " ", "g"]
];
var port = process.env.PORT || 8000;
// Create the app
// ------------------
var app = express()
var router = express.Router({
mergeParams: true
})
// Add the routes
// ------------------
router.get('/plot', function (request, response) {
// Create the path
var path = request.params[0].
split('').
map(function (direction) {
return {
n: 'north',
w: 'west',
s: 'south',
e: 'east'
}[direction]
}).
join(', then ');
response.send('You plan to travel ' + path + '.');
});
router.get('/travel', function (request, response) {
// Calculate the initial position
var currentX;
var currentY;
var maxX = (travelMap[0] || []).length - 1;
var maxY = (travelMap || []).length - 1;
travelMap.map(function (row, yIndex) {
sIndex = row.indexOf('s');
if (sIndex > -1) {
currentX = sIndex;
currentY = yIndex;
}
});
// Calculate the journey
request.params[0].
split('').
map(function (direction) {
var change = {
n: {x: 0, y: -1},
w: {x: -1, y: 0},
s: {x: 0, y: 1},
e: {x: 1, y: 0}
}[direction]
currentX += change.x;
currentY += change.y;
if (currentY < 0 || currentY > maxY || currentX < 0 || currentX > maxX) {
response.send('You fell off a cliff.');
}
if (travelMap[currentY][currentX].toLowerCase() === 'g') {
response.send(
'You walked straight into a grue and were devoured. ' +
'It was...Grue-some');
}
});
if (travelMap[currentY][currentX].toLowerCase() === 'e') {
response.send(
emoji.emojify('You maaaaaaaaadeee iiiit! :information_desk_person:'));
}
response.send("You haven't been eaten...yet.");
});
// Only match on valid journey routes
app.use(/\/([nwse]+)/, router);
// Start the app
app.listen(port, function () {
console.log('App running on port ' + port);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment