toHexShort utility (#119)

This commit is contained in:
Jaco Greeff
2018-04-23 09:34:31 +02:00
committed by GitHub
parent f1095fc4e4
commit 68e77f3abb
6 changed files with 76 additions and 8 deletions
+2
View File
@@ -13,6 +13,7 @@ const u8aFromString = require('./fromString');
const u8aToBn = require('./toBn');
const u8aToBuffer = require('./toBuffer');
const u8aToHex = require('./toHex');
const u8aToHexShort = require('./toHexShort');
const u8aToString = require('./toString');
const u8aToU8a = require('./toU8a');
const u8aToUtf8 = require('./toUtf8');
@@ -31,6 +32,7 @@ module.exports = {
u8aToBn,
u8aToBuffer,
u8aToHex,
u8aToHexShort,
u8aToString,
u8aToU8a,
u8aToUtf8
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
// @flow
/**
@name u8aToHexShort
@signature u8aToHexShort (value?: UInt8Array, max: number = 16): string
@summary Creates a hex string from a Uint8Array object with max characters.
@description
`UInt8Array` input values return the actual hex string shortened to the specified characters. `null` or `undefined` values returns an `0x` string.
@example
import { u8aToHexShort } from '@polkadot/util';
u8aToHexShort(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0xf]), 4); // 0x68...0f
*/
module.exports = function u8aToHex (value?: Uint8Array, max: number = 16): string {
if (!value || !value.length) {
return '0x';
}
const interim = value.reduce((result, item) => {
return result + ('0' + item.toString(16)).slice(-2);
}, '');
if (interim.length <= max) {
return `0x${interim}`;
}
const mid = Math.floor(max / 2);
return `0x${interim.substr(0, mid)}...${interim.slice(-1 * mid)}`;
};
+33
View File
@@ -0,0 +1,33 @@
// Copyright 2017-2018 Jaco Greeff
// This software may be modified and distributed under the terms
// of the ISC license. See the LICENSE file for details.
const { u8aToHexShort } = require('./index');
describe('u8aToHexShort', () => {
const input = new Uint8Array([1, 2, 3, 4, 5, 0, 6, 7, 8, 9]);
it('returns empty as 0x', () => {
expect(
u8aToHexShort()
).toEqual('0x');
});
it('returns the hex value for the array (max >= length)', () => {
expect(
u8aToHexShort(input, 20)
).toEqual('0x01020304050006070809');
});
it('returns the hex value for the array (max (default) < length)', () => {
expect(
u8aToHexShort(input)
).toEqual('0x01020304...06070809');
});
it('returns the hex value for the array (max < length)', () => {
expect(
u8aToHexShort(input, 10)
).toEqual('0x01020...70809');
});
});