From fb0b1ac00407dc87682146d10aa36857418e9f12 Mon Sep 17 00:00:00 2001 From: Timo Hocker Date: Fri, 24 Apr 2020 16:57:50 +0200 Subject: [PATCH] tests, padding --- index.js | 8 ++++++-- test/index.js | 21 +++++++++++++++++++++ 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 47b4157..3d9d205 100644 --- a/index.js +++ b/index.js @@ -50,10 +50,14 @@ function to_hex (str, encoding = '') { * encode a number to hex * * @param {number} n number to encode + * @param {number} padding minumum length of output * @returns {string} hex */ -function num_to_hex (n) { - return n.toString (16); +function num_to_hex (n, padding = 0) { + const res = n.toString (16); + if (res.length < padding) + return '0'.repeat (padding - res.length) + res; + return res; } /** diff --git a/test/index.js b/test/index.js index 9c5aad6..0adc243 100644 --- a/test/index.js +++ b/test/index.js @@ -6,6 +6,7 @@ */ // @ts-nocheck +/* eslint-disable no-magic-numbers */ 'use strict'; const test = require ('ava'); @@ -26,3 +27,23 @@ test ('encoding to_utf8', (t) => { const utf = encoding.to_utf8 ('Zm9v', 'base64'); t.is (utf, 'foo'); }); + +test ('convert num to hex', (t) => { + const res = encoding.num_to_hex (11); + t.is (res, 'b'); +}); + +test ('convert num to hex padded', (t) => { + const res = encoding.num_to_hex (11, 2); + t.is (res, '0b'); +}); + +test ('convert hex to num', (t) => { + const res = encoding.hex_to_num ('b'); + t.is (res, 11); +}); + +test ('convert hex padded to num', (t) => { + const res = encoding.hex_to_num ('0b'); + t.is (res, 11); +});