diff --git a/src/draw.js b/src/draw.js index f1f1a1f..0b67173 100644 --- a/src/draw.js +++ b/src/draw.js @@ -1,29 +1,34 @@ -import * as mongodb from 'mongodb'; import { strategies } from './strategies'; -const MongoClient = mongodb.MongoClient; +class Strategies { + constructor() { + this.reset(); + this.shuffle(); + } -const drawCard = async () => { - const url = 'mongodb://localhost:27017'; - const dbName = 'oblique'; + reset() { + this.cards = strategies; + } - const client = await MongoClient.connect(url, { useNewUrlParser: true }); - const db = client.db(dbName); - const cardCounts = db.collection('counts'); + shuffle() { + const { cards } = this; + let f = cards.length, y; - const theCard = strategies[ Math.floor(Math.random()*strategies.length) ].toLowerCase(); - const trackingName = theCard.replace(/\W/g, ''); + while (f) { + y = Math.floor(Math.random() * f--); + [cards[f], cards[y]] = [cards[y], cards[f]]; + } - const updated = await cardCounts.findOneAndUpdate( - { card: trackingName }, - { $set: { card: trackingName }, $inc: { count: 1 } }, - { upsert: true, returnNewDocument: true }, - ); + return this; + } - client.close(); - return theCard; + draw() { + const drawn = this.cards.pop(); + if (this.cards.length === 0) this.reset(); + return drawn.toLowerCase(); + } } module.exports = { - drawCard, + Strategies, } diff --git a/src/index.js b/src/index.js index 2d60de1..cf558d6 100644 --- a/src/index.js +++ b/src/index.js @@ -6,15 +6,18 @@ import express from 'express'; import bodyParser from 'body-parser'; import moment from 'moment'; -import { drawCard } from './draw'; +import { Strategies } from './draw'; const app = express(); app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json()); +const strategies = new Strategies(); + app.get('/', async (req, res) => { - const theStrategy = await drawCard(); + const theStrategy = strategies.draw(); + const theTree = ` @@ -59,7 +62,7 @@ app.post('/', async (req, res, next) => { }, } - const theStrategy = encodeURIComponent(await drawCard()); + const theStrategy = encodeURIComponent(strategies.draw()); var theResponseRequest = https.request( {