S
S
SideWest2019-08-04 14:12:21
JavaScript
SideWest, 2019-08-04 14:12:21

What is the best way to save command parameters?

I am writing a bot, users send a command with parameters.
It looks something like this:

var text = '#перевести Лёша 100'
    text = text.split('#')
    text.shift()
    text = text[0].split(' ')
    console.log(text);

As a result, I have an array of the form:
[ 'translate', 'Lesha', '100' ]

Tell me how best to store the parameters of such a command? What if the other command has more parameters? Is it possible to write a universal handling of such a thing?
And what is the best way to implement this?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stockholm Syndrome, 2019-08-04
@SideWest

set a description for each command

const commands = [{
  name: 'transfer',
  value: /#перевести/i,
  separator: / /,
  params: ['name', 'count']
}, /* ... */];

and get the name and parameters of the command in the normal form
const parse = (msg) => {
  const command = commands.find((item) => (msg.match(item.value) || {}).index === 0);
  if (!command) {
    return null;
  }

  const args = msg.split(command.separator).slice(1);
  return {
    name: command.name, 
    params: command.params.reduce((acc, curr, i) => ({...acc, [curr]: args[i] || null}), {})
  };
};


parse('#перевести Лёша 100'); 
/* 
  {
    name: 'transfer', 
    params: {
      name: 'Лёша',
      count: '100'
    }
  }
*/

D
Dmitry Derepko, 2019-08-04
@xEpozZ

It can be stored in a similar object:

{
    command: "перевести",
    params: ["Лёша", 100]
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question