@js-data-tools/js-helpers
Version:
A set of JavaScript / TypeScript helper functions for parsing, converting, transforming and formatting data.
59 lines (58 loc) • 1.93 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.macAddressAsNumber = exports.macAddressAsString = void 0;
const bigint255 = BigInt(255);
const bigint8 = BigInt(8);
const macDelimiterPattern = /[-:]/g;
function macAddressAsString(mac, format) {
const delimiter = format === undefined ? "-" : format;
if (typeof mac === "string") {
if (mac.length !== 12 && mac.length !== 17) {
throw new Error("Input of bad length. MAC address string should be either 12 or 17 characters long");
}
if (!delimiter) {
if (mac.length === 12) {
return mac;
}
return mac.replace(macDelimiterPattern, "");
}
if (mac.length === 12) {
return (mac.substring(0, 2) +
delimiter +
mac.substring(2, 4) +
delimiter +
mac.substring(4, 6) +
delimiter +
mac.substring(6, 8) +
delimiter +
mac.substring(8, 10) +
delimiter +
mac.substring(10, 12));
}
if (mac[2] !== delimiter) {
return mac.replace(macDelimiterPattern, delimiter);
}
return mac;
}
if (typeof mac !== "bigint") {
throw new Error("Input should be either string or bigint");
}
const tokens = new Array(6);
let current = mac;
for (let i = 5; i >= 0; --i) {
tokens[i] = (current & bigint255).toString(16).padStart(2, "0");
current >>= bigint8;
}
return tokens.join(delimiter);
}
exports.macAddressAsString = macAddressAsString;
function macAddressAsNumber(mac) {
if (typeof mac === "number") {
return mac;
}
if (typeof mac === "bigint") {
return mac;
}
return BigInt("0x" + mac.replace(/[-:]/g, ""));
}
exports.macAddressAsNumber = macAddressAsNumber;