Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

176
Views
SumFileSizes function

Friends, help with the task.

I need to write a function that takes the names of two files and calls the function passed in the third parameter and passes it the sum of their sizes as the first argument.

To get the file frame, you need to use the getFileSize (filename, cb) function.

Here is the data:

let fileSizes = {
  testFile1: 65,
  testFile2: 48,
}

function getFileSize(filename, cb) {
  setTimeout(() => cb(fileSizes[filename]), Math.random() * 500);
}

function sumFileSizes(filename1, filename2, cb) {
  //**code here**
}

I wrote a solution that passes the tests. But I don't like it.

Here it is:

function sumFileSizes(filename1, filename2, cb) {
    getFileSize(filename1, (size1)=> {
        getFileSize(filename2, (size2)=> {
            cb(size1 + size2);
        });
    })
}

Can you write something better and shorter? And without using a promise or await .

I'll be very thankful

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Not sure if you want something like this or not but I believe you can return Promise with size of given filename, and in handler calculate the size.

Here in your example, I have created sumFileSizes where you will get the final number. getFileSize returns new promise which you can use it in sumFileSizes method for each file.

See the Snippet below:

let fileSizes = {
  testFile1: 65,
  testFile2: 48,
}

sumFileSizes("testFile1", "testFile2", getSum).then(_sum => {
    console.log(_sum);
})


function getFileSize(fileName){
  return new Promise((resolve, reject) => {
     resolve(fileSizes[fileName]);
  });
}

function sumFileSizes(fileName1, fileName2, fn){
    return getFileSize(fileName1).then((size1)=> {
      const _total =  getFileSize(fileName2).then((size2)=> {
          return fn(size1, size2);
      });
      
      return _total;
  });
}

function getSum(a,b){
    return a+b;
}




/*function getFileSize(filename, cb) {
  cb(fileSizes[filename]);
}

function sumFileSizes(filename1, filename2, cb) {
  //**code here**
}

function sumFileSizes(filename1, filename2, cb) {
    getFileSize(filename1, (size1)=> {
        getFileSize(filename2, (size2)=> {
            cb(size1 + size2);
        });
    })
}*/

You can test it here also.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!