JSFiddle - React, Tailwind, and code Playground

by Krzysztof Safjanowski

JavaScript

/*
 * any user can try to buy a gun
 * the gun can be sell according to law rules
 *  * for Poland, min age 18
 *  * for USA, min age 21
 */

class Countries {
  constructor() {
    this.counties = []
  }

  add(country) {
    this.counties.push(country)
  }
}

class Country {
  constructor(name, minimumAge) {
    this.name = name
    this.minimumAge = minimumAge
  }

  checkRequirements(self) {
    if (userAge() > this.minimumAge) {
      return true
    } else {
      throw new Error(`Required age is ${this.minimumAge}`)
    }

    function userAge() {
      return new Date(Date.now()).getFullYear() - self.age.getFullYear()
    }
  }
}

let poland = new Country('Poland', 18)
let usa = new Country('USA', 21)

let countries = new Countries()

countries.add(poland)
countries.add(usa)

class User {
  constructor(country, age) {
    this.country = country
    this.age = age
  }

  buyAGun() {
    return this.country.checkRequirements(this)
  }
}

let userOne = new User(poland, new Date(2000, 2, 3))
let userTwo = new User(poland, new Date(1998, 2, 3))
let userThree = new User(usa, new Date(1997, 2, 3))
let userFourth = new User(usa, new Date(1995, 2, 3))

~[userOne, userTwo, userThree, userFourth].forEach(user => {
  try {
    console.log('user bought a gun', user.buyAGun())
  } catch (e) {
    console.log('we have got issue', e.message)
  }
})