How to iterate over account history items

Words
120
Reading
1 min
Listen
Play
9y

Using steem.js, it is easy to iterate over all the history items of an account. However, if you have not done this before, it may be a little tricky, because there is not enough documentation on the web (or maybe I didn’t find it).

Anyway, steem.api.getAccountHistory returns a promise that resolves to a batch of history items. Each item has an ID number (that starts with 1 for the first item in the history). The batch returned is sorted ascendingly, and contains limit + 1 items, starting at from. If you want to start at the most recent item, you can give from a value of -1. Otherwise, from must be larger than or equal to limit.

Here is an example code for getting history items:

    for (let from = -1, limit = 100, going = true; !!from && going; ) {
        let items = await steem.api.getAccountHistory(username, from, Math.min(limit, from));
        from = items[0][0] - 1;
        items.reverse();
        loop:
        for (let item of items) {
            if (someTest(item)) {
                going = false;
                break loop;
            }
            // do something with item
        }
    }

The loop ends if we reach the first item (hence the use of !!from) or if someTest(item) returns true.

How to iterate over account history items | Ecency