1

I've written some ugly code which will verify whether I can query an object.

const quoterContract = getQuoterContract(quoterAddress, QuoterABI, provider);
const quotePromises = poolData.map(data => {
    const dataEnclosure = data;
    const quote = getQuotedPrice(quoterContract, tradeAmount, data.token0, data.token1, data.feeAmount ?? 0)
        .then(r =>{
            dataEnclosure.isQuotable = true;
            return dataEnclosure; 
        })
        .catch(err => { 
            dataEnclosure.isQuotable = false
            return dataEnclosure;
        });
    return quote;
})

const quoteData = await Promise.all(quotePromises)

quoteData.forEach(d => {
    console.log(` ${d.name} is quotable ${d.isQuotable}`);
});

//Function pseudo code for clarification
const getQuotedPrice = async (a,b,c,d) => {...}

This is very ugly and verbose, and I'd like to simplify, however I don't think asyc iterables exist in typescript. Is there a simpler way to write this?

Ritzy Dev
  • 387
  • 3
  • 10
  • TS does support async iterables, but they don't seem to be applicable here. Your code looks pretty reasonable except for the unnecessary `dataEnclosure` and `quote` variables, which could be omitted without any loss of clarity – CertainPerformance Nov 14 '22 at 23:54
  • @CertainPerformance don't I need to enclose the data variable or I will always end up updating the last data? Or is that javascript only and the code will work fine in TS – Ritzy Dev Nov 15 '22 at 00:19
  • 1
    What you're concerned about is only a thing if you're declaring a variable with `var`, and you're inside a non-function block. https://stackoverflow.com/questions/750486 That's not the case here. – CertainPerformance Nov 15 '22 at 00:24
  • 1
    This is better suited for https://codereview.stackexchange.com . "ugly" is quite subjective, and doesn't describe the problem or the desired outcome. – Eric Haynes Nov 15 '22 at 04:35

1 Answers1

1

Does this look any cleaner to you? ;)

import {pipeAsync, map, wait} from 'iter-ops';

const quoterContract = getQuoterContract(quoterAddress, QuoterABI, provider);

const quoteData = pipeAsync(
  poolData,
  map(dataEnclosure => {
     const {token0, token1, feeAmount = 0} = dataEnclosure;
     return getQuotedPrice(quoterContract, tradeAmount, token0, token1, feeAmount)
        .then(r => {
            dataEnclosure.isQuotable = true;
            return dataEnclosure;
        })
        .catch(err => {
            dataEnclosure.isQuotable = false
            return dataEnclosure;
        });
 }),
 wait()
);

for await (const d of quoteData) {
    console.log(`${d.name} is quotable ${d.isQuotable}`);
}
vitaly-t
  • 24,279
  • 15
  • 116
  • 138