Repository navigation
Expand file tree
/
Copy pathtransform-array.js
More file actions
53 lines (50 loc) · 1.71 KB
/
Copy pathtransform-array.js
File metadata and controls
53 lines (50 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
const { NotImplementedError } = require('../extensions/index.js');
/**
* Create transformed array based on the control sequences that original
* array contains
*
* @param {Array} arr initial array
* @returns {Array} transformed array
*
* @example
*
* transform([1, 2, 3, '--double-next', 4, 5]) => [1, 2, 3, 4, 4, 5]
* transform([1, 2, 3, '--discard-prev', 4, 5]) => [1, 2, 4, 5]
*
*/
function transform(arr){
if(Array.isArray(arr)){
let result =[];
if(arr.some((item) => typeof item === "string")){
for (let i=0; i<arr.length; i++){
let lastElement = result[result.length -1];
if(arr[i] === "--double-prev"){
if(typeof arr[i-1] === 'number' && arr[i-2] !== "--discard-next"){
console.log('a');
result.push(lastElement);
}
}else if(arr[i] === "--discard-prev"){
if(typeof arr[i-1] === 'number'){
result.pop();
}
}else if(arr[i] === "--double-next"){
if(typeof arr[i+1] === 'number'){
result.push(arr[i+1]);
}
}else if(arr[i] === "--discard-next"){
if(typeof (arr.indexOf('--discard-next')+1) === 'number'){
arr.splice((arr.indexOf('--discard-next')+1),1);
}
}else {
result.push(arr[i]);
}
}
}else {return arr;}
return result;
} else {
throw new Error("'arr' parameter must be an instance of the Array!")
}
}
module.exports = {
transform
};