Move deck to a class with shuffle/reset methods.
This commit is contained in:
parent
2c39b83733
commit
4ef4194d3e
41
src/draw.js
41
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,
|
||||
}
|
||||
|
@ -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 =
|
||||
`<!doctype html>
|
||||
<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(
|
||||
{
|
||||
|
Loading…
Reference in New Issue
Block a user