@polkadot/util
Version:
A collection of useful utilities for @polkadot
39 lines (38 loc) • 1.42 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.u8aToU8a = void 0;
const toU8a_js_1 = require("../hex/toU8a.js");
const buffer_js_1 = require("../is/buffer.js");
const hex_js_1 = require("../is/hex.js");
const u8a_js_1 = require("../is/u8a.js");
const toU8a_js_2 = require("../string/toU8a.js");
/**
* @name u8aToU8a
* @summary Creates a Uint8Array value from a Uint8Array, Buffer, string or hex input.
* @description
* `null` or `undefined` inputs returns a `[]` result, Uint8Array values returns the value, hex strings returns a Uint8Array representation.
* @example
* <BR>
*
* ```javascript
* import { u8aToU8a } from '@polkadot/util';
*
* u8aToU8a(new Uint8Array([0x12, 0x34]); // => Uint8Array([0x12, 0x34])
* u8aToU8a(0x1234); // => Uint8Array([0x12, 0x34])
* ```
*/
function u8aToU8a(value) {
return (0, u8a_js_1.isU8a)(value)
// NOTE isBuffer needs to go here since it actually extends
// Uint8Array on Node.js environments, so all Buffer are Uint8Array,
// but Uint8Array is not Buffer
? (0, buffer_js_1.isBuffer)(value)
? new Uint8Array(value)
: value
: (0, hex_js_1.isHex)(value)
? (0, toU8a_js_1.hexToU8a)(value)
: Array.isArray(value)
? new Uint8Array(value)
: (0, toU8a_js_2.stringToU8a)(value);
}
exports.u8aToU8a = u8aToU8a;
;