0

Write code to "safely" calculate the perimeter and area of a rectangle. The sides of a rectangle can only be a number (data type Number, values of other data types cannot be set), the value of which is strictly greater than 0. Code must be in Secure Closure format. Why doesn't validation work in my code that values are strictly greater than 0 and how to validate that there are only numbers

function createPOWandS() {
  var x = 0;
  var y = 0;
  var arr = [];
  arr[0] = function(newSum) {
    if (newSum >= 0) {
      x = newSum;
      y = newSum;
    }
  };
  arr[1] = function() {
    return 2 * (x + y);
  };
  arr[2] = function() {
    return x * y;
  }
  return arr;
}

var sqrt = createPOWandS();
sqrt[0](2, 2);
console.log(sqrt[1]());
sqrt[0](2, 2);
console.log(sqrt[2]());
kosmodraiv
  • 29
  • 3

1 Answers1

0

I restructured your function to show the three functions being returned. What you have here is called a "thunk". A function that returns a function, except you are returning an array of unnamed functions.

To "reveal" what the functions do, I destructured the resulting array into a setter, perimeter, and area function.

I also added a try-catch error handling example for invalid inputs.

const isNumeric = (n) => !isNaN(n - parseFloat(n));
const isValid = (n) => isNumeric(n) && n > 0;

const createPOWandS = () => {
  const state = { x: 0, y: 0 };
  return [
    (x, y) => {
      if (!isValid(x) || !isValid(y)) {
        throw new Error(`Illegal arguments: (${x}, ${y})`);
      }
      Object.assign(state, { x: x, y: y });
    },
    () => 2 * (state.x + state.y),
    () => state.x * state.y
  ];
};

// Invalid
{
  const [setter, calcPerimiter, calArea] = createPOWandS();
  try {
    setter('A', false);
  } catch (e) {
    console.log(e.message);
  }
}

// Valid
{
  const [setter, calcPerimiter, calArea] = createPOWandS();
  setter(2, 3);
  console.log('Perimiter:', calcPerimiter());
  console.log('Area:', calArea());
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132