Computers are insane. I was inspired by the comments to shard out the keys to many objects so I would not hit the 8M key limit in JavaScript. I then used GitHub Copilot to write this code in about 30 seconds, just using comments and having Copilot write the rest:
// Find the files we want to count
let files = NodeFileSystem.readdirSync('data/imported');
let keyArray = [];
let keyArrayLength = 0;
// Add all of the keys to an array
for(let file of files) {
if(file.endsWith('.json')) {
console.log('Parsing file', file);
let data = JSON.parse(NodeFileSystem.readFileSync('data/imported/'+file));
// Add the data item.key to the array
for(let item of data) {
keyArray.push(item.key);
keyArrayLength++;
}
}
}
console.log('Total array length:', keyArrayLength);
// JavaScript will only allow us to have 8 million keys in an object, so we need to shard the array
// into several objects, using the first characters of each key
let characterCountToUseForSharding = 2;
// An object to store the sharded objects
let shardedObjects = {};
// Loop through the key array
let processedCount = 0;
for(let key of keyArray) {
processedCount++;
if(processedCount % 1000000 === 0) {
let processCountWithCommas = processedCount.toLocaleString();
console.log('Processed', processCountWithCommas, 'of', keyArrayLength.toLocaleString());
}
// Get the first characterCountToUseForSharding characters of the key
let shardingKey = key.substring(0, characterCountToUseForSharding);
// If the sharded object doesn't exist, create it
if(!shardedObjects[shardingKey]) {
shardedObjects[shardingKey] = {};
// console.log('Created sharded object', shardingKey);
}
// Add the key to the sharded object
shardedObjects[shardingKey][key] = true;
}
// Count the keys in each sharded object
let total = 0;
for(let shardingKey in shardedObjects) {
let keyCount = Object.keys(shardedObjects[shardingKey]).length;
console.log('Sharding key', shardingKey, 'has', keyCount, 'keys');
total += keyCount;
}
// Log the total
console.log('Total keys:', keyArrayLength);
console.log('Total unique keys:', total);
// Percentage
let percentage = (total / keyArrayLength) * 100;
console.log('Unique percentage:', percentage);
// Duplicate keys
let duplicateKeys = keyArrayLength - total;
console.log('Duplicate keys:', duplicateKeys);
Here you can see the output and speed:
https://www.youtube.com/watch?v=RurzxMjbazg
I am running it on an M1 MacBook Pro and just amazed at the speed. The fan did not even turn on.
uniq
in bash stackoverflow.com/questions/23740545/…, althoughsort
will be slow