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
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.