settingsAccountsettings
By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy
Menusettings

Q: List Processor (task with JavaScript object composition)

+1 vote

Using a closure, create an inner object to process list commands. The commands supported should be the following:

  • add <string> - adds the following string in an inner collection.
  • remove <string> - removes all occurrences of the supplied <string> from the inner collection.
  • print - prints all elements of the inner collection joined by ", ".

Input:
The input will come as an array of strings - each string represents a command to be executed from the command execution engine.

Output:
For every print command - you should print on the console the inner collection joined by ", "

Examples:

Sample Input:

['add hello', 'add again', 'remove hello', 'add again', 'print']

Output:

again,again


Sample Input:

['add pesho', 'add gosho', 'add pesho', 'remove pesho','print']

Output:

gosho

asked in JavaScript category by user andrew

1 Answer

0 votes

Here is the solution below:

function processList(commands) {

    let commandProcessor = (function () {
        let list = [];
        return {
            add: (newItem) => list.push(newItem),
            remove: (item) => list = list.filter(x => x != item),
            print: () => console.log(list)
        }
    })();

    for (let cmd of commands) {
        let [cmdName,arg] = cmd.split(" ");
        commandProcessor[cmdName](arg);
    }
}

processList(['add hello', 'add again', 'remove hello', 'add again', 'print']);
processList(['add pesho', 'add gosho', 'add pesho', 'remove pesho', 'print']);

 

answered by user hues
...