Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function arrayManipulator(numbers, commands) {
- for (let command of commands) {
- let tokens = command.split(" ");
- let currentCommand = tokens[0];
- if (currentCommand === "add") {
- let index = Number(tokens[1]);
- let element = Number(tokens[2]);
- numbers.splice(index, 0, element);
- } else if (currentCommand === "addMany") {
- let index = Number(tokens[1]);
- let setOfElements = tokens.slice(2, tokens.length);
- numbers.splice(index, 0, ...setOfElements);
- } else if (currentCommand === "contains") {
- let result = numbers.indexOf(+tokens[1])
- console.log(result);
- } else if (currentCommand === "remove") {
- let index = Number(tokens[1]);
- numbers.splice(index, 1)
- } else if (currentCommand === "shift") {
- let positions = Number(tokens[1]);
- for (let i = 0; i < positions; i++) {
- let first = numbers.shift();
- numbers.push(first);
- }
- } else if (currentCommand === "sumPairs") {
- let resultArr = [];
- if (numbers.length % 2 !== 0) {
- numbers.push(0);
- }
- for (let i = 0; i < numbers.length - 1; i += 2) {
- let sum = numbers[i] + numbers[i + 1];
- resultArr.push(sum)
- }
- numbers = resultArr;
- } else if (currentCommand === "print") {
- console.log(`[ ${numbers.map(Number).join(", ")} ]`);
- }
- }
- //console.log(`[ ${numbers.map(Number).join(", ")} ]`);
- }
- arrayManipulator(
- [1, 2, 4, 5, 6, 7],
- ['add 1 8', 'contains 1', 'contains 3', 'print'])
- // 0
- // -1
- // [ 1, 8, 2, 4, 5, 6, 7 ]
- // arrayManipulator([1, 2, 3, 4, 5],
- // ['addMany 5 9 8 7 6 5', 'contains 15', 'remove 3', 'shift 1', 'print'])
- // -1
- // [ 2, 3, 5, 9, 8, 7, 6, 5, 1 ]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement