Sample filter / map / reduce (XRP Transaction Sum)
/*
Filter / Map / Reduce on arrays:
Imagine a funnel
`filter`, `map`, `reduce`:
They take an array as input and at the other send the input is returned processed.
filter = decide what should be in the output array
map = modify the content of each object that will be in the output array
reduce = aggregate the input to some output
*/
const RippleAPI = require('ripple-lib').RippleAPI
const api = new RippleAPI({ server: 'wss://rippled.xrptipbot.com' })
api.connect().then(() => {
return api.getTransactions('rPdvC6ccq8hCdPKSPJkPmyZ4Mi1oG2FFkT', {
minLedgerVersion: 36542093
}).then(transactions => {
// `transactions` is an array with transaction objects.
let sum =
transactions
.filter(tx => {
// The .filter runs for each tx in transactions, we call each
// transaction (each array member) 'tx'. Only return true
// (so: array object to next part of the chain) if this is valid
return tx.type === 'payment'
&& tx.outcome.result === 'tesSUCCESS'
&& tx.outcome.deliveredAmount.currency === 'XRP'
})
.map(tx => {
// Convert to drops, prevent rounding errors
let value = parseFloat(tx.outcome.deliveredAmount.value) * 1000000
return Math.round(value)
})
.reduce((existingTotal, thisValue) => {
return existingTotal + thisValue
}, 0) // 0 = 2nd argument = startValue
console.log('Sum in XRP:', sum / 1000000)
})
}).then(() => {
}).catch(console.error)
no comments