30-Days-Of-JavaScript icon indicating copy to clipboard operation
30-Days-Of-JavaScript copied to clipboard

how to write good code for this example

Open alicera opened this issue 3 years ago • 0 comments

Thanks for your document. I have some question.

I input two number. It will search the num1.csv to response to result value. And add it.

case1: Input: 1 , 2 process: 1 => 10, 2 => 20 output: 10 + 20 = 30

case2: Input: 1 , 2 , 3, 4 process: 1 => 10, 2 => 20, 3 => 30, 4 => 40 output: 10 + 20 +30 + 40 = 100

How can I optimize the code when add some input?

Test.js

// require csvtojson module
const CSVToJSON = require('csvtojson');


function compute() {
    let input = 1;
    getNum1(input).then(output => {
        //console.log(output);
        input = 2 ;
        getNum1(input).then(output2 => {
        let finalResult = parseInt(output) + parseInt(output2)
        console.log(finalResult);
        })
    })
}


async function csv2json(csvFilePath) {
    return jsonArray = await CSVToJSON().fromFile(csvFilePath);
}

function getNum1(input) {
    return csv2json('num1.csv').then((blob) => {
        for (var obj in blob) {
            if (blob[obj]['input'] == input) {
                let result = blob[obj]['result'];
                return result;
            }
        }
    }).catch(e => console.log(e));
}


compute()

num1.csv

input,result
5,50
4,40
3,30
2,20
1,10

alicera avatar Mar 11 '22 10:03 alicera