最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Question about returning a function as 'undefined' given a negative number? - Stack Overflow

programmeradmin0浏览0评论

I'm trying to write code that will return undefined if given a negative number

I was asked to calculate the areas of a rectangle, triangle and circle using a function in Javascript. I got that part right but the problem also says "If any of the parameters are negative, the function should return undefined."

function calculateRectangleArea (length, width) {
  return length * width;
}
function calculateTriangleArea (base, height) {
  return (base * height)/2;
}
function calculateCircleArea (radius) {
  return radius * radius * Math.PI;
}

I can calculate the areas fine but I can't figure out what to write if there is a negative number to get undefined. Is it something like:

if (calculateRectangleArea <0) 
   return "undefined";

I'm trying to write code that will return undefined if given a negative number

I was asked to calculate the areas of a rectangle, triangle and circle using a function in Javascript. I got that part right but the problem also says "If any of the parameters are negative, the function should return undefined."

function calculateRectangleArea (length, width) {
  return length * width;
}
function calculateTriangleArea (base, height) {
  return (base * height)/2;
}
function calculateCircleArea (radius) {
  return radius * radius * Math.PI;
}

I can calculate the areas fine but I can't figure out what to write if there is a negative number to get undefined. Is it something like:

if (calculateRectangleArea <0) 
   return "undefined";
Share Improve this question edited Feb 17, 2019 at 23:49 Rasanjana N 1,4001 gold badge13 silver badges32 bronze badges asked Feb 17, 2019 at 22:04 astudenyastudeny 312 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 4

You need to test each parameter to make sure it's not negative, in an if statement, and if any are negative, return undefined - else, return the ordinary calculation like you're already doing:

function calculateRectangleArea(length, width) {
  if (length < 0 || width < 0) {
    return undefined;
  } else {
    return length * width;
  }
}
function calculateTriangleArea(base, height) {
  if (base < 0 || height < 0) {
    return undefined;
  } else {
    return (base * height) / 2;
  }
}
function calculateCircleArea(radius) {
  if (radius < 0) {
    return undefined;
  } else {
    return radius * radius * Math.PI;
  }
}

Alternatively, since when no value is returned, undefined is returned by default, you could also only return the calculation if all parameters are non-negative, eg:

function calculateRectangleArea(length, width) {
  if (length >= 0 && width >= 0) {
    return length * width;
  }
}

Because you want it to happen if any of the parameters are undefined, use some on [...arguments]:

function calculateRectangleArea (length, width) {
  if ([...arguments].some(e => e < 0)) return undefined;
  return length * width;
}

Do this for all your functions.

The easiest and most readable solution is checking that all arguments are positive before calculating the area, otherwise you will return undefined.

For example (this is using the conditional operator):

function calculateRectangleArea (length, width) {
  return length < 0 || width < 0 ? undefined: length * width;
}

function calculateTriangleArea (base, height) {
  return base < 0 || height < 0 ? undefined : (base * height)/2;
}

function calculateCircleArea (radius) {
  return radius < 0 ? undefined: radius * radius * Math.PI;
}

(Note: for the circle you could use the exponential operator, where supported)

Since you have defined a mon pattern for all the calculations, you could generalize.

Basically, you could define a "guard" where you execute the given function only if the arguments are positive, otherwise you will return undefined. That kind of checking could be applied to all your calculations, despite the arguments and the math involved. That is possible because JS has First-class functions.

The following example is using the spread syntax and arrow function but they could be done with regular function too:

// Takes a function as argument and returns a function 
// that will execute the function given only if all the arguments
// provided are positive, `undefined` otherwise:
const guard = fn => (...args) => args.some(arg => arg < 0) ? undefined : fn(...args);

const calculateRectangleArea = guard((length, width) => length * width);
const calculateTriangleArea = guard((base, height) => base * height /2);
const calculateCircleArea = guard(radius => radius ** 2 * Math.PI);

You use Math.abs() to check if an integer or decimal is negative. The code defines the functions as properties of an object, and a function which uses .find() to create a variable which is set as undefined if one of the parameters passed to the function is negative

const calculations = {
  calculateRectangleArea (length, width) {
    const n = this[Object.getOwnPropertySymbols(this)[0]](length, width) 
    return !n ? n : length * width
  },
  calculateTriangleArea (base, height) {
    const n = this[Object.getOwnPropertySymbols(this)[0]](base, height) 
    return !n ? n : (base * height)/2
  },
  calculateCircleArea (radius) { 
    const n = this[Object.getOwnPropertySymbols(this)[0]](radius) 
    return !n ? n : radius * radius * Math.PI
  },
  [Symbol('filter')](...props) {
    const n = props.find(n => Math.abs(n) !== n)
    // if `n` is not `undefined` `return` `void 0` else return `true`
    console.log(!n)
    return n !== undefined ? void 0 : !n
  }
}

console.log(
  calculations.calculateRectangleArea(0, 0) // `0`
, calculations.calculateTriangleArea(1, 2) // `1` 
, calculations.calculateCircleArea(-2, 1) // `undefined`
)

I just wanted to say thank you for all of this help! I managed to solve it but it is really helpful to have this munity willing to step in and assist! I hope one day I will be good enough to return the favour.

Thanks!

发布评论

评论列表(0)

  1. 暂无评论