Skip to content

Instantly share code, notes, and snippets.

@oharsta
Created October 8, 2014 15:19
Show Gist options
  • Save oharsta/5a3dbf79868067f13ef8 to your computer and use it in GitHub Desktop.
Save oharsta/5a3dbf79868067f13ef8 to your computer and use it in GitHub Desktop.
'use strict';
angular.module('portal')
.factory('PrefixCalculator', function () {
/**
* Sums up the prefixLengths given a specified bitSize
*
* @param prefixes prefixLength integers (e.g. 22, 39 etc)
* @param bitSize the bitSize of the IP (e.g. 32 or 128)
* @returns {number} the total of the prefixLength
*/
var doSumIpvX = function (prefixes, bitSize) {
var addressSizes = _.map(prefixes, function (prefix) {
return Math.pow(2, bitSize - prefix);
});
var totalAddressSize = _.reduce(addressSizes, function (total, addressSize) {
return total + addressSize;
});
var sumIpvX = (bitSize - (Math.log(totalAddressSize) / Math.log(2)));
return Math.floor(sumIpvX);
};
return {
sumIpv4: function (ipv4Prefixes) {
return doSumIpvX(ipv4Prefixes, 32);
},
sumIpv6: function (ipv6Prefixes) {
return doSumIpvX(ipv6Prefixes, 128);
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment