Javascript在计算形状面积方面的承诺

时间:2019-07-16 08:41:06

标签: javascript

我想使用Javascript Promises计算各种几何形状的面积。 形状为正方形,矩形,圆形和三角形。可以使用以下公式计算每个区域的面积:

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

这是我到目前为止所做的,但未通过测试

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;
        }
    })
}

它返回一个Promise,成功时将返回所有形状的区域数组,失败时将返回[-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);
    })
}

样本输入

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

样本输出

4
12 
78.5 
4

6 个答案:

答案 0 :(得分:0)

您的圈子应使用类似的计算方式:

values[0] * values[0] * 3.14

(而不是values[0] * values[1] * 3.14),因为圆的输入中只有一个值。


我相信您的括号末尾放错了位置-应该是

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

(而不是computeArea(shapes [i],values_arr [i] .then ...)


最后,在getAreas中,new Promise(async( ...似乎是多余的,因为Promises本质上是异步的。也许尝试删除asyncawait,因为您是直接创建自己的Promise。

(请查看这篇相当详尽的文章,以了解更多信息: https://medium.com/@bluepnume/learn-about-promises-before-you-start-using-async-await-eb148164a9c8

答案 1 :(得分:0)

我仍然不知道这些承诺是什么。你不需要它们

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];
});

但是,如果您坚持要这么做,您仍然可以使getAreas异步(如所评论),您将获得承诺。

答案 2 :(得分:0)

您只是遇到了一些数学和语法错误。没什么大不了的,您可以继续:

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));

请考虑在将来用于异步任务,因为code is written for humans不是计算机,我们作为人类在阅读该代码时会尝试查找并了解不存在的代码的异步属性,因为您决定使用诺言。

答案 3 :(得分:0)

这是使用Javascript Promise编写getArea函数的另一种方法:

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;
    });
}

答案 4 :(得分:0)

您在 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);

答案 5 :(得分:0)

存在一些计算问题,这就是为什么要使用NaN的原因,我希望这可以解决问题。

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));