-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse-an-array-without-affecting-special-characters.js
47 lines (44 loc) · 1.54 KB
/
reverse-an-array-without-affecting-special-characters.js
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
/*
Following problem is implemented from here.
http://www.geeksforgeeks.org/reverse-an-array-without-affecting-special-characters/
Author : NNSatyaKarthik
*/
var splitSpecialCharacters = function(input){
var ichars = '/[~`!#$%\^&*+=\-\[\]\\\';,/{}|\\":<>\?]/';
var normalChars = "";
var specialChars = "";
input.split('').map(function(x){
if(ichars.indexOf(x) > -1){
normalChars += " ";
specialChars += x;
}else{
normalChars += x;
specialChars += " ";
}
});
return [normalChars, specialChars];
};
var getReversedStringWithoutSpecialCharsReplacement = function(input){
var splitArrays = splitSpecialCharacters(input);
var normalChars = splitArrays[0];
var specialChars = splitArrays[1];
var reversedNormal = normalChars.split('').map(function(x){
if(x !== ' '){
return x;
}
}).reverse().join('');
var specialCharsArr = specialChars.split('');
reversedNormal.split('').map(function(x){
var idx = specialCharsArr.indexOf(' ');
// console.log(idx, specialChars)
if(idx != -1){
specialCharsArr[idx] = x;
}
});
return specialCharsArr.join('');
};
var startTime = new Date().getTime();
var input = "Ab,c,de!$";
var output = getReversedStringWithoutSpecialCharsReplacement(input);
var endTime = new Date().getTime();
console.log("Reverse of this "+input+" string without moving positions of special chars is "+ output +" found in : "+(endTime - startTime)+" milliseconds!");