H
H
heisenberg12021-06-10 13:03:51
JavaScript
heisenberg1, 2021-06-10 13:03:51

How to rewrite the code so that the function gets the values ​​of the object's keys?

There is this code:

const style = [
  'palace',
  'flat',
  'house',
  'bungalow',
  'hotel'
]; 
const register = [
  '12:00',
  '13:00',
  '14:00'
]; 
const check = [
  '12:00',
  '13:00',
  '14:00'
];
function getRandomFixedValues(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
function random(style, register , check) {
  return (style[getRandomFixedValues(0, style.length - 1)]) + ', ' +  (register[getRandomFixedValues(0, register.length - 1)]) + ', ' +  (check[getRandomFixedValues(0, check.length - 1)])
};
console.log(random(style, register , check));

It produces the desired result, how can it be rewritten so that style, register and check are not separate arrays, but keys of a certain object (for example, general)?

For functions to apply to:

const general= {
style: [
  'palace',
  'flat',
  'house',
  'bungalow',
  'hotel'
], 
register: [
  '12:00',
  '13:00',
  '14:00'
],
check: [
  '12:00',
  '13:00',
  '14:00'
]};

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexander, 2021-06-10
@Seasle

const general = {
  style: ['palace', 'flat', 'house', 'bungalow', 'hotel'],
  register: ['12:00', '13:00', '14:00'],
  check: ['12:00', '13:00', '14:00'],
};

- function random(style, register , check) {
+ function random({ style, register, check }) {

- console.log(random(style, register , check));
+ console.log(random(general));

Also, you can simplify getting a random element:
const pick = array => array[Math.floor(Math.random() * array.length)];
pick(['Apple', 'Orange']); // 'Apple' или 'Orange'

Then you can write like this:
function random({ style, register , check }) {
    return pick(style) + ', ' +  pick(register) + ', ' + pick(check);
};
// Или так:
// const random = ({ style, register , check }) => `${pick(style)}, ${pick(register)}, ${pick(check)}`;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question