0

I am building a factory function to manage Ship objects for a battleship game. So far I have the following:

    const Ship = (name, length, orientation = 'horizontal') => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = (position) => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  return {
    name,
    length,
    orientation,
    sunk,
    hits,
    hit,
    sink,
  };
};

I am testing the sink() method to change the sunk property boolean from false to true. However, whenever I run:

example.sink() example.sunk sunk always remains false.

Where am I going wrong?

For some reason the hit() method alters the hits propertyfine. Butsink()is not altering thesunk` property.

Thanks

5
  • How did you invoke the method? Commented Aug 25, 2021 at 8:13
  • 1
    sunk is a boolean value, not an array ref like hits. The object returned by Ship isn't re-evaluated, so the value will always be the same. Commented Aug 25, 2021 at 8:13
  • Thanks, so how can I achieve what I am looking to do? Commented Aug 25, 2021 at 8:14
  • You can create getter and setter for sunk property. Commented Aug 25, 2021 at 8:15
  • @LearningPython I'd probably take a quick step back and find some good JS OOP tutorials, then decide which JS OOP approach you want to take. There are several ways this could be approached. Commented Aug 25, 2021 at 8:17

2 Answers 2

1

You can use getters to retrieve the values:

const Ship = (name, length, orientation = 'horizontal') => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = position => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  return {
    name,
    length,
    orientation,
    hit,
    sink,
    // get values using getters
    get sunk() { return sunk; },
    get hits() { return hits; },
  };
};

const someShip = Ship(`ss something`, 100, `vertical`);
someShip.sink();
console.log(someShip.sunk);

Sign up to request clarification or add additional context in comments.

Comments

0

You can create a API method to access the local sunk method

const Ship = (name, length, orientation = "horizontal") => {
  let sunk = false;
  const hits = Array(length).fill(false);

  const hit = (position) => {
    if (position <= hits.length) hits[position] = true;
  };

  function sink() {
    sunk = true;
  }

  function getSunk() {
    return sunk;
  }

  return {
    name,
    length,
    orientation,
    hits,
    hit,
    sink,
    getSunk,
  };
};

const ship = Ship("a", 10);
console.log(ship.getSunk());
ship.sink();
console.log(ship.getSunk());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.