Move deck to a class with shuffle/reset methods.

This commit is contained in:
nicholas 2019-06-06 22:12:28 -04:00
parent 2c39b83733
commit 4ef4194d3e
2 changed files with 29 additions and 21 deletions

View File

@ -1,29 +1,34 @@
import * as mongodb from 'mongodb';
import { strategies } from './strategies'; import { strategies } from './strategies';
const MongoClient = mongodb.MongoClient; class Strategies {
constructor() {
this.reset();
this.shuffle();
}
const drawCard = async () => { reset() {
const url = 'mongodb://localhost:27017'; this.cards = strategies;
const dbName = 'oblique'; }
const client = await MongoClient.connect(url, { useNewUrlParser: true }); shuffle() {
const db = client.db(dbName); const { cards } = this;
const cardCounts = db.collection('counts'); let f = cards.length, y;
const theCard = strategies[ Math.floor(Math.random()*strategies.length) ].toLowerCase(); while (f) {
const trackingName = theCard.replace(/\W/g, ''); y = Math.floor(Math.random() * f--);
[cards[f], cards[y]] = [cards[y], cards[f]];
}
const updated = await cardCounts.findOneAndUpdate( return this;
{ card: trackingName }, }
{ $set: { card: trackingName }, $inc: { count: 1 } },
{ upsert: true, returnNewDocument: true },
);
client.close(); draw() {
return theCard; const drawn = this.cards.pop();
if (this.cards.length === 0) this.reset();
return drawn.toLowerCase();
}
} }
module.exports = { module.exports = {
drawCard, Strategies,
} }

View File

@ -6,15 +6,18 @@ import express from 'express';
import bodyParser from 'body-parser'; import bodyParser from 'body-parser';
import moment from 'moment'; import moment from 'moment';
import { drawCard } from './draw'; import { Strategies } from './draw';
const app = express(); const app = express();
app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json()); app.use(bodyParser.json());
const strategies = new Strategies();
app.get('/', async (req, res) => { app.get('/', async (req, res) => {
const theStrategy = await drawCard(); const theStrategy = strategies.draw();
const theTree = const theTree =
`<!doctype html> `<!doctype html>
<html lang='en'> <html lang='en'>
@ -59,7 +62,7 @@ app.post('/', async (req, res, next) => {
}, },
} }
const theStrategy = encodeURIComponent(await drawCard()); const theStrategy = encodeURIComponent(strategies.draw());
var theResponseRequest = https.request( var theResponseRequest = https.request(
{ {