Add basic u8aToString (#92)
This commit is contained in:
@@ -13,6 +13,7 @@ const u8aFromString = require('./fromString');
|
||||
const u8aToBn = require('./toBn');
|
||||
const u8aToBuffer = require('./toBuffer');
|
||||
const u8aToHex = require('./toHex');
|
||||
const u8aToString = require('./toString');
|
||||
const u8aToUtf8 = require('./toUtf8');
|
||||
|
||||
/**
|
||||
@@ -29,5 +30,6 @@ module.exports = {
|
||||
u8aToBn,
|
||||
u8aToBuffer,
|
||||
u8aToHex,
|
||||
u8aToString,
|
||||
u8aToUtf8
|
||||
};
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// 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 u8aToString
|
||||
@signature u8aToString (value?: UInt8Array): string
|
||||
@summary Creates a string from a Uint8Array object.
|
||||
@description
|
||||
`UInt8Array` input values return the actual decoded string. `null` or `undefined` values returns an empty string.
|
||||
@example
|
||||
import { u8aToString } from '@polkadot/util';
|
||||
|
||||
u8aToString(new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])); // hello
|
||||
*/
|
||||
module.exports = function u8aToString (value?: Uint8Array): string {
|
||||
if (!value || !value.length) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return value
|
||||
.reduce((result, ch) => {
|
||||
result.push(String.fromCharCode(ch));
|
||||
|
||||
return result;
|
||||
}, [])
|
||||
.join('');
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
// 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 { u8aToString } = require('./index');
|
||||
|
||||
describe('u8aToString', () => {
|
||||
it('decodes to an empty string for undefined', () => {
|
||||
expect(
|
||||
u8aToString()
|
||||
).toEqual('');
|
||||
});
|
||||
|
||||
it('decodes to an empty string for empty buffer', () => {
|
||||
expect(
|
||||
u8aToString(new Uint8Array([]))
|
||||
).toEqual('');
|
||||
});
|
||||
|
||||
it('decodes the buffer correctly', () => {
|
||||
expect(
|
||||
u8aToString(
|
||||
new Uint8Array([0x68, 0x65, 0x6c, 0x6c, 0x6f])
|
||||
)
|
||||
).toEqual('hello');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user