Last active
April 27, 2020 18:03
-
-
Save MartinsOnuoha/57798bb901662dd2882831f766a95564 to your computer and use it in GitHub Desktop.
Solution to Encoded Blocks of transactions problem.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Get previous transactions from last transaction | |
* @param last { Object } | |
*/ | |
const getPrevTransactions = (last) => { | |
let all = [] | |
all.push(last); | |
if (last.previousBlock) { | |
let hasPrev = true; | |
while (hasPrev) { | |
let lastIn = all[all.length - 1]; // get the last pushed transaction; | |
// decode the prev tranx from the last given | |
let prevTranx = JSON.parse(Buffer.from(lastIn.previousBlock, 'base64').toString()) | |
prevTranx.previousBlock ? | |
all.push(prevTranx) : hasPrev = false; | |
} | |
all = [...new Set(all)].reverse() // remove duplicates if any and reverse transaction list | |
} | |
return all; | |
} | |
/** | |
* get transaction by specified field | |
* @param type { String } | |
* @param query { String } | |
*/ | |
const getTransactionByAny = (transactions, by = '_id', query) => { | |
const allowedFields = ['id', '_id', 'ref', 'txRef']; | |
if (!allowedFields.includes(by)) { | |
return 'query field not allowed' | |
} | |
by === 'id' ? by = '_id' : ''; // autocorrect user ( 🙂 ) | |
return transactions.find(tranx => tranx[`${by.trim()}`] === query); | |
} | |
/** | |
* filter transactions by given field | |
* @param transactions { Array } | |
* @param by { String } | |
* @param query { string } | |
*/ | |
const filterTransactionsByAny = (transactions, by = 'amount', query = '100') => { | |
const allowedFilters = ['address', 'amount', 'status', 'createdAt']; | |
if (!allowedFilters.includes(by)) { | |
return 'query field not allowed' | |
} | |
return transactions.filter(tranx => tranx[`${by.trim()}`] === query); | |
} | |
/** | |
* get the sum of filtered transactions | |
* @param filtered { Array } | |
*/ | |
const sumFiltered = (filtered) => { | |
return filtered.reduce((acc, curr) => curr.amount ? acc + Number(curr.amount) : acc + 0, 0); | |
} | |
// insert last transaction | |
const lastTranx = {} | |
const transactions = getPrevTransactions(lastTranx); | |
const filtered = filterTransactionsByAny(transactions, 'address', '1HSY7V2P488zb93ok9jWikmXwKCrQwcChC') | |
const tranx = getTransactionByAny(transactions, 'address', '1HSY7V2P488zb93ok9jWikmXwKCrQwcChC') | |
sumFiltered(filtered) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment