2018-12-17 12:37:00 +08:00
/**
* @author tcode2k16 [tcode2k16@gmail.com]
* @copyright Crown Copyright 2018
* @license Apache-2.0
*/
2019-07-09 12:23:59 +01:00
import Operation from "../Operation.mjs" ;
2018-12-17 12:37:00 +08:00
import BigNumber from "bignumber.js" ;
2019-07-09 12:23:59 +01:00
import Utils from "../Utils.mjs" ;
2018-12-17 12:37:00 +08:00
/**
* From Base62 operation
*/
class FromBase62 extends Operation {
/**
* FromBase62 constructor
*/
constructor () {
super ();
this . name = "From Base62" ;
this . module = "Default" ;
2018-12-18 12:19:42 +00:00
this . description = "Base62 is a notation for encoding arbitrary byte data using a restricted set of symbols that can be conveniently used by humans and processed by computers. The high number base results in shorter strings than with the decimal or hexadecimal system." ;
this . infoURL = "https://wikipedia.org/wiki/List_of_numeral_systems" ;
2018-12-17 12:37:00 +08:00
this . inputType = "string" ;
2018-12-18 12:19:42 +00:00
this . outputType = "byteArray" ;
this . args = [
{
name : "Alphabet" ,
type : "string" ,
value : "0-9A-Za-z"
}
];
2018-12-17 12:37:00 +08:00
}
/**
* @param {string} input
* @param {Object[]} args
2018-12-18 12:19:42 +00:00
* @returns {byteArray}
2018-12-17 12:37:00 +08:00
*/
run ( input , args ) {
2018-12-18 12:19:42 +00:00
if ( input . length < 1 ) return [];
2019-11-13 17:59:16 +00:00
const alphabet = Utils . expandAlphRange ( args [ 0 ]). join ( "" );
const BN62 = BigNumber . clone ({ ALPHABET : alphabet });
2018-12-17 12:37:00 +08:00
2019-11-13 17:59:16 +00:00
const re = new RegExp ( "[^" + alphabet . replace ( /[[\]\\\-^$]/g , "\\$&" ) + "]" , "g" );
2018-12-17 12:37:00 +08:00
input = input . replace ( re , "" );
2019-11-13 17:59:16 +00:00
// Read number in using Base62 alphabet
const number = new BN62 ( input , 62 );
// Copy to new BigNumber object that uses the default alphabet
const normalized = new BigNumber ( number );
2018-12-17 12:37:00 +08:00
2019-11-13 17:59:16 +00:00
// Convert to hex and add leading 0 if required
let hex = normalized . toString ( 16 );
if ( hex . length % 2 !== 0 ) hex = "0" + hex ;
return Utils . convertToByteArray ( hex , "Hex" );
2018-12-17 12:37:00 +08:00
}
}
export default FromBase62 ;