Skip to content

Instantly share code, notes, and snippets.

@Townsheriff
Last active March 18, 2018 20:56
Show Gist options
  • Select an option

  • Save Townsheriff/854f24157ff0c944d4476f953752e668 to your computer and use it in GitHub Desktop.

Select an option

Save Townsheriff/854f24157ff0c944d4476f953752e668 to your computer and use it in GitHub Desktop.
Find most popular AS in BGP table (empty and 0 first results should be ignored)
'use strict';
const fs = require('fs');
const split = require('split');
const through = require('through');
const regex = /\*\>?\s+[\d+|\.]+\/\d+\s+[\d+|\.]+\s+([\d+\s]+)/;
const filter = through(function(buffer) {
const line = buffer.toString();
if (line.match(regex)) {
this.queue(line);
}
});
const popularity = new Map();
const longest = through(function(buffer) {
const line = buffer.toString();
const results = line.match(regex);
const current = new Set(results[1].split(' '));
current.forEach((id) => {
if (!popularity.has(id)) {
popularity.set(id, 1);
return;
}
const count = popularity.get(id);
popularity.set(id, count + 1);
});
});
longest.on('close', () => {
const values = [0, 0, 0, 0, 0];
const keys = [-1, -1, -1, -1, -1];
popularity.forEach((value, key) => {
for(let i = 0; i < values.length; i++) {
if (values[i] <= value) {
console.log(`Popular AS: ${key} and it's popularity is: ${value}`);
for(let j = values.length - 2; j >= i; j--) {
values[j + 1] = values[j];
keys[j + 1] = keys[j];
}
values[i] = value;
keys[i] = key;
break;
}
}
});
console.log(keys);
console.log(values);
});
const fileStream = fs.createReadStream('ipv4bgp2018apnic.txt');
fileStream
.pipe(split())
.pipe(filter)
.pipe(longest)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment