Created
March 8, 2020 23:04
-
-
Save TroublesNCuddles/e25d0967dbe0d657ec7fbbb5e1a44a1b to your computer and use it in GitHub Desktop.
This file contains 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 {MongoClient} = require('mongodb'); | |
const MONGODB_URI = 'mongodb://localhost:27017/KoalatyEconomy'; | |
const LOWEST_NUMBER = '0000000'; | |
const MAX_NUMBER = 9999999; | |
const MAX_BATCH_SIZE = 98000; | |
const AREA_CODES = [420, 469]; | |
const generateNumbers = (area_codes) => { | |
let numbers = []; | |
for (let index = 0; index < area_codes.length; index++) { | |
area_codes[index] = parseInt(`${area_codes[index]}${LOWEST_NUMBER}`); | |
} | |
for (let count = 0; (count + parseInt(LOWEST_NUMBER)) < MAX_NUMBER; count++) { | |
area_codes.forEach(code => { | |
numbers.push(code + count); | |
}); | |
} | |
return numbers; | |
}; | |
const shuffle = (array) => { | |
for (let i = array.length - 1; i > 0; i--) { | |
let j = Math.floor(Math.random() * (i + 1)); | |
[array[i], array[j]] = [array[j], array[i]]; | |
} | |
}; | |
const connect = async () => { | |
return await MongoClient.connect(MONGODB_URI, { | |
useNewUrlParser: true, | |
useUnifiedTopology: true | |
}); | |
}; | |
connect() | |
.then(async mongodb_client => { | |
let numbers = generateNumbers(AREA_CODES); | |
let run = true; | |
console.log(numbers.length.toLocaleString() + ' generated...'); | |
shuffle(numbers); | |
try { | |
const collection = mongodb_client.db().collection('phone_numbers'); | |
let c = 1; | |
await collection.createIndex({number: 1}, {unique: true}); | |
while (run) { | |
let batch = numbers.slice(0, MAX_BATCH_SIZE); | |
numbers = numbers.slice(MAX_BATCH_SIZE); | |
console.log(`Inserting batch #${c} [${batch.length.toLocaleString()}]. Approximately ${Math.ceil(numbers.length / MAX_BATCH_SIZE)} batches left...`); | |
if (batch.length === 0) { | |
run = false; | |
continue; | |
} | |
for (let index = 0; index < batch.length; index++) { | |
batch[index] = {number: batch[index], assigned: false}; | |
} | |
console.time(`Batch #${c} completed...`); | |
await collection.insertMany(batch); | |
console.timeEnd(`Batch #${c} completed...`); | |
c++; | |
} | |
} finally { | |
await mongodb_client.close(); | |
} | |
}) | |
.catch(error => { | |
console.log(error); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment