Skip to content

Instantly share code, notes, and snippets.

@pedrouid
Created December 8, 2019 14:46
Show Gist options
  • Save pedrouid/b7eb2975093adb8227f1675245848e54 to your computer and use it in GitHub Desktop.
Save pedrouid/b7eb2975093adb8227f1675245848e54 to your computer and use it in GitHub Desktop.
Recursive Parse (BigNumber example)
const BigNumber = require("bignumber.js");
let test = {
initialState: {
amount: {
_hex: "0x4563918244f40000",
},
assetId: "0xeec918d74c746167564401103096D45BbD494B74",
coinTransfers: [
{
amount: {
_hex: "0x4563918244f40000",
},
to: "0xf80D16ea04D24bf0A2a45d5101E62BE5681240ff",
},
{
amount: {
_hex: "0x00",
},
to: "0xF80fd6F5eF91230805508bB28d75248024E50F6F",
},
],
linkedHash: "0x8edf857e1cfa97682d7ef0277a98b159c899da66b75955435df9b3e4289d0b76",
paymentId: "0x9f915492bb490ec3096b5616e65fd0ea287fe76993335f5e32698777fa6873bc",
preImage: "0x0000000000000000000000000000000000000000000000000000000000000000",
},
};
function recursiveParse(evalObj: any, isCondition: any, parse: any) {
const result = evalObj;
function crawlAndParse(
evalObj: any,
isCondition: any,
parse: any,
prevObj?: any,
prevKey?: string,
) {
if (!isCondition(evalObj, prevObj, prevKey) && typeof evalObj === "object") {
Object.keys(evalObj).map(key =>
crawlAndParse(evalObj[key], isCondition, parse, evalObj, key),
);
} else {
if (isCondition(evalObj, prevObj, prevKey)) {
prevObj[prevKey] = parse(prevObj[prevKey]);
}
}
}
crawlAndParse(result, isCondition, parse);
return result;
}
function isCondition(evalObj: any, prevObj?: any, prevKey?: string) {
if (typeof evalObj === "object") {
const keys = Object.keys(evalObj);
if (keys.length === 1 && keys[0] === "_hex") {
return true;
}
}
return false;
}
function parse(evalObj: any) {
return new BigNumber(evalObj._hex);
}
let result = recursiveParse(test, isCondition, parse);
console.log(result)
// {
// initialState: {
// amount: [BigNumber],
// assetId: "0xeec918d74c746167564401103096D45BbD494B74",
// coinTransfers: [
// {
// amount: [BigNumber],
// to: "0xf80D16ea04D24bf0A2a45d5101E62BE5681240ff",
// },
// {
// amount: [BigNumber],
// to: "0xF80fd6F5eF91230805508bB28d75248024E50F6F",
// },
// ],
// linkedHash: "0x8edf857e1cfa97682d7ef0277a98b159c899da66b75955435df9b3e4289d0b76",
// paymentId: "0x9f915492bb490ec3096b5616e65fd0ea287fe76993335f5e32698777fa6873bc",
// preImage: "0x0000000000000000000000000000000000000000000000000000000000000000",
// },
// };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment