Commit 627a623c authored by Aral Balkan's avatar Aral Balkan
Browse files

Codes being generated and saved correctly.

parent ea4b5936
shorthash = require 'shorthash'
uuid = require 'uuid'
fs = require 'fs'
class CodeGenerator
folder: null
constructor: ->
# We put codes generated in each session into their own timestamped folder so we
# do not accidentally overwrite earlier ones
@folder = 'codes/' + Date.now()
fs.mkdirSync @folder
generateUniqueCodes: (numCodes) =>
codes = []
while numCodes
uniqueCode = uuid.v4() + '-' + Date.now()
shortUniqueCode = shorthash.unique(uniqueCode)
codes.push shortUniqueCode
numCodes--
return codes
generateUniqueCodesAndSaveToFile: (numCodes, fileNameToSaveTo) =>
codes = @generateUniqueCodes(numCodes)
fileNameJSON = @folder + '/' + fileNameToSaveTo + '.json'
fs.writeFileSync fileNameJSON, JSON.stringify(codes)
module.exports = CodeGenerator
\ No newline at end of file
CodeGenerator = require './CodeGenerator.coffee'
codeGenerator = new CodeGenerator()
codeGenerator.generateUniqueCodesAndSaveToFile 1000, 'tier-100'
codeGenerator.generateUniqueCodesAndSaveToFile 1000, 'tier-1000'
......@@ -2,7 +2,7 @@
"name": "waystone-codes",
"version": "1.0.0",
"description": "Generates codes for Waystone",
"main": "generate.coffee",
"main": "generate-codes.coffee",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
......@@ -12,6 +12,8 @@
"author": "Aral Balkan",
"license": "Closed Source (this needs to be private)",
"dependencies": {
"shorthash": "0.0.2"
"assert": "^1.1.2",
"shorthash": "0.0.2",
"uuid": "^2.0.1"
}
}
assert = require 'assert'
CodeGenerator = require './CodeGenerator.coffee'
#
# Implementation of hash sieve algorithm that I read
# about at http://www.shamasis.net/2009/09/fast-algorithm-to-find-unique-items-in-javascript-array/
# in CoffeeScript with slightly more literate code :)
#
Array.prototype.unique = ->
hashSieve = {}
arrayOfUniqueValues = [];
for item in @
hashSieve[item] = item
for item of hashSieve
arrayOfUniqueValues.push item
return arrayOfUniqueValues
#
# Test that codes really are unique.
#
codeGenerator = new CodeGenerator()
codes = codeGenerator.generateUniqueCodes(1000)
codes = codes.unique()
assert.equal codes.length, 1000, 'There should be 1,000 unique codes.'
#
# And that our hash sieve is working :)
#
codes[0] = 'Hello'
codes[1] = 'Hello'
codes = codes.unique()
assert.equal codes.length, 999, 'There should be 999 unique codes.'
console.log 'TESTS OK.'
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment