-
-
Save jrson83/18dc3b35e06a38d29dabd3c0a9a14593 to your computer and use it in GitHub Desktop.
Small node program reading each keystroke from the command line
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const readline = require('readline'); | |
| const stdin = process.stdin; | |
| readline.emitKeypressEvents(stdin); | |
| stdin.setRawMode(true); | |
| class Coordinates { | |
| constructor(x = 0, y = 0) { | |
| this.x = x; | |
| this.y = y; | |
| } | |
| incrementY() {this.y += 1} | |
| decrementY() {this.y -= 1} | |
| incrementX() {this.x += 1} | |
| decrementX() {this.x -= 1} | |
| toString() {return `[${this.x}, ${this.y}]`} | |
| } | |
| const coordinates = new Coordinates(); | |
| stdin.on('keypress', function (_, key) { | |
| handleKey(key, process); | |
| }); | |
| const handleKey = (key, process) => { | |
| if (key) { | |
| switch (key.name) { | |
| case 'up': | |
| coordinates.incrementY(); | |
| break; | |
| case 'down': | |
| coordinates.decrementY(); | |
| break; | |
| case 'left': | |
| coordinates.decrementX(); | |
| break; | |
| case 'right': | |
| coordinates.incrementX(); | |
| break; | |
| case 'c': | |
| if (key.ctrl) { | |
| process.exit() | |
| } | |
| } | |
| console.log(`New coordinates: ${coordinates.toString()}`) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment