简体   繁体   中英

Javascript Promise in calculating area of a shape

I want to use Javascript Promises to calculate the areas of various geometrical shapes. The shapes are square, rectangle, circle and triangle. The area of each can be computed using these formulas:

Square of side a : Area = a2(asqure)
Rectangle of length 'I' and width ‘w’: Area = w x I
Circle of radius ‘r’: Area = Pi x r2 (rsquare)
Triangle of base ‘b’ and height ‘h’: Area = 0.5 x b x h

This is what I have done so far but not passing the test

let calculateArea = (shapes, values) => {
    return new Promise((resolve, reject) => {
        switch(shapes) {
            case 'square':
                resolve(values[0]*values[1]);
                break;

            case 'rectangle':
                resolve(values[0]*values[1]);
                break;
            case 'circle':
                resolve(values[0]*values[1] * 3.14);
                break;
                case 'triangle':
                resolve(0.5 * values[0]*values[1]);
                break;
            default:
                reject([-1]);
                break;
        }
    })
}

It returns a Promise which on success, returns an array of areas of all the shapes and on failure, returns [-1].

let getAreas = (shapes, values_arr) => {
    return new Promise(async(resolve, reject) => {
        let areas_array = [];
        for(let i=0; i < shapes.length; i++) {
            await calculateArea(shapes[i],values_arr[i].then(area => {
                areas_array.push(area);
            }).catch(error => {
                return reject(error);
            }))
        }
        resolve(areas_array);
    })
}

The sample input

2
square
rectangle
circle
triangle
2
3,4
5 
2,4

Sample Output

4
12 
78.5 
4

Your circle should use a calculation like:

values[0] * values[0] * 3.14

(instead of values[0] * values[1] * 3.14 ) since there is only a single value in the input for circle.


And I believe you have a misplaced end-parenthesis -- it should be:

calculateArea(shapes[i],values_arr[i]).then ...

(instead of calculateArea(shapes[i],values_arr[i].then ...)


Finally, in getAreas, new Promise(async( ... seems redundant since Promises are asynchronous by nature. Perhaps try removing async and await since you're creating your own Promises directly.

(Check out this fairly thorough, if somewhat dated, article for more clarification: https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8 )

I still don't know what it is with those promises. You don't need them

let getAreas = /*async*/(shapes, values) => shapes.map((shape, i) => {
  const factor = {
    square: 1,
    rectangle: 1,
    circle: Math.PI,
    triangle: .5
  }[shape];

  const [a, b = a] = values[i];

  if (factor) {
    return a * b * factor;
  }

  throw [-1];
});

but if you insist, you can still make getAreas async (as commented) and you'll get your Promise.

you just have some math and syntax errors..no big deals, here you go:

let calculateArea = (shapes, values) => {
    return new Promise((resolve, reject) => {
        switch (shapes) {
            case 'square':
                resolve(values[0] * values[1]);
                break;

            case 'rectangle':
                resolve(values[0] * values[1]);
                break;
            case 'circle':
                resolve(values[0] * 22 / 7);
                break;
            case 'triangle':
                resolve(0.5 * values[0] * values[1]);
                break;
            default:
                reject([-1]);
                break;
        }
    })
}

let getAreas = (shapes, values_arr) => {

    return new Promise(async (resolve, reject) => {
        let areas_array = [];

        for (let i = 0; i < shapes.length; i++) {
            await calculateArea(shapes[i], values_arr[i])
                    .then(area => {
                        areas_array.push(area);
                    }).catch(error => {
                        return reject(error);
                    })
        }
        resolve(areas_array);
    })

}

getAreas(
[
    'square',
    'rectangle',
    'circle',
    'triangle'
],
[
    [2,2],
    [3,4],
    [5],
    [2,4],
]
).then(result => console.log(result))
.catch(error => console.log(error));

please consider using promises for async tasks in the future because code is written for humans not the computers and we as humans when we read that code we try looking and understanding the async property of the code that doesn't exist because you decide to use promise.

Here's another way to write the getArea function using Javascript Promise:

let getAreas = async (shapes, values_arr) => {
    const areaPromises = shapes.map(async (shape, index) => {
        //calculate area for each shape data 
        const response = await calculateArea(shape, values_arr[index]);
        return response;
    });
    return Promise.all(areaPromises).then(result => {
        return result;
    });
}

You don't need a promise in getAreas() :

   let calculateArea = (shape, values) => {
      return new Promise((resolve, reject) => {
        switch(shape) {
          case 'square':
            console.log("It's a square with a=" +values[0]);
            resolve(values[0]*values[0]);
            break;
          case 'rectangle':
            console.log("It's a rectangle with a=" + values[0] + " and b=" + values[1]);
            resolve(values[0] * values[1]);
            break;
          case 'circle':
            console.log("It's a circle with r=" + values[0]);
            resolve(values[0]*values[0] * 3.14);
            break;
          case 'triangle':
            console.log("It's a triangle with b=" + values[0]+ " and h=" + values[1] )
            resolve(0.5 * values[0]*values[1]);
            break;
          default:
            reject([-1]);
            break;
        }
      })
    }

    let getAreas = (shapes, values_arr) => {    
    let areas_array = [];
    for(let i= 0; i < shapes.length; i++) {
      calculateArea(shapes[i], values_arr[i])
       .then(area => {
         areas_array.push(area);
        })
        .catch(error => {
          return reject(error);
        })
    }
    console.log(areas_array);
    };


    let shapes = ["square", "rectangle", "circle", "triangle"];
    let values_arr = [[2], [3, 4], [5], [2, 4]];
    getAreas(shapes, values_arr);

There is some calculation problems which is why it is giving NaN, I hope this solves the problem.

let calculateArea = (shapes, values) => {
  return new Promise((resolve, reject) => {
        switch (shapes) {
            case 'square':
                       resolve(values[0] * values[0]);
                break;
            case 'rectangle':
                resolve(values[0] * values[1]);
                break;
            case 'circle':
                resolve(values[0] * values[0] * 3.14);
                break;
            case 'triangle':
                resolve(0.5 * values[0] * values[1]);
                break;
            default:
                reject([-1]);
                break;
        }
    });
}


// Complete the generateArea function below.
// It returns a Promise which on success, returns an array of areas of all the shapes and on failure, returns [-1].
let getAreas = (shapes, values_arr) => {

     return new Promise(async (resolve, reject) => {
        let areas_array = [];

        for (let i = 0; i < shapes.length; i++) {
            await calculateArea(shapes[i], values_arr[i])
                    .then(area => {
                        areas_array.push(area);
                    }).catch(error => {
                        return reject(error);
                    });
        }
        resolve(areas_array);
    });

}

getAreas(
[
    'square',
    'rectangle',
    'circle',
    'triangle'
],
[
    [2,2],
    [3,4],
    [5],
    [2,4],
]
).then(result => console.log(result))
.catch(error => console.log(error));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM