Kuby Block

Blog about programming, tech, society and more.

Let's talk

poster

Implement an discussion

In a room, there are several people - Person. Each person has some attributes and stands next to others, in a coutinuous row:

class Person {
  #name = "";
  #gender = "M";
  #age = 0;
  #messages = [];
  #nextPerson = null;

  constructor({ name, gender, age, messages }) {
    this.#name = name;
    this.#gender = gender;
    this.#age = age;
    this.#messages = messages;
  }

  set next(anotherPerson) {
    this.#nextPerson = anotherPerson;
  }

  get message() {
    const randIdx = Math.floor(Math.random() * this.#messages.length);
    return this.#messages[randIdx];
  }
}

And of course, everyone has the ability to speak and hear:

class Person {
  // ... some code ...

  speak(oldMessages) {
    const message = this.message;

    console.log(`${this.#name} says: `);
    console.log(`-- heard messages: ${oldMessages}`);
    console.log(`... and says: ${message}`);

    if (this.#nextPerson) {
      this.#nextPerson.hear([...oldMessages, message]);
    }
  }

  hear(messages) {
    this.speak(messages);
  }
}

When a person speaks, his next person will hear. And when they hear, they will have to repeat all what they hear and speak more one sentence of themselves.

Everyone kept talking circle like that until the final person.

Initiate a discussion

Let initiate a discussion with several people and necessary information:

function initPeople() {
  const people = [
    new Person({
      name: "Linda",
      gender: "F",
      age: 22,
      messages: ["hello", "good morning", "welcome"]
    }),
    new Person({
      name: "Barbara",
      gender: "M",
      age: 23,
      messages: [
        "today is so cold",
        "not just an idea",
        "walk by one leg",
        "this is so far"
      ]
    }),
    new Person({
      name: "Yayin",
      gender: "M",
      age: 30,
      messages: ["green side of the world", "a good cake"]
    }),
    new Person({
      name: "Imouto",
      gender: "F",
      age: 25,
      messages: [
        "fruit is not the vegetable",
        "a ball on the water",
        "sugar is not sweet"
      ]
    })
  ];

  for (let index = 0; index < people.length - 1; ++index) {
    people[index].next = people[index + 1];
  }

  return people;
}

Ok, everything is ready, let start joining the discussion:

(function main() {
  const people = initPeople();

  const startPersonIdx = Math.floor(Math.random() * people.length);
  const startPerson = people[startPersonIdx];
  const startMessage = "go!";
  startPerson.speak([startMessage]);
})();

and as result, we will see:

Barbara says:
-- heard messages: go!
... and says: today is so cold
Yayin says:
-- heard messages: go!,today is so cold
... and says: green side of the world
Imouto says:
-- heard messages: go!,today is so cold,green side of the world
... and says: fruit is not the vegetable

comments powered by Disqus