-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathalt-split.js
More file actions
45 lines (39 loc) · 1.57 KB
/
alt-split.js
File metadata and controls
45 lines (39 loc) · 1.57 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
// Simple Encryption #1 - Alternating Split
// DESCRIPTION:
// Implement a pseudo-encryption algorithm which given a string S and an integer N concatenates all the odd-indexed characters of S with all the even-indexed characters of S, this process should be repeated N times.
// Examples:
// encrypt("012345", 1) => "135024"
// encrypt("012345", 2) => "135024" -> "304152"
// encrypt("012345", 3) => "135024" -> "304152" -> "012345"
// encrypt("01234", 1) => "13024"
// encrypt("01234", 2) => "13024" -> "32104"
// encrypt("01234", 3) => "13024" -> "32104" -> "20314"
// Together with the encryption function, you should also implement a decryption function which reverses the process.
// If the string S is an empty value or the integer N is not positive, return the first argument without changes.
function encrypt(text, n) {
if(n <= 0 || !text){
return text
}
let odd = text.split("").filter((elem,i) => i % 2 ===1)
let even = text.split("").filter((elem,i) => i % 2 === 0)
return encrypt(odd.concat(even).join(""), n-1)
}
function decrypt(encryptedText, n) {
if(n <= 0|| !encryptedText){
return encryptedText
}
let splitNum = encryptedText.length/2
let odd = encryptedText.slice(0,splitNum)
let even = encryptedText.slice(splitNum)
let newText = []
for(let i = 0; i < encryptedText.length; i++){
if(i % 2 === i-1){
newText.push(odd[i])
newText.push(even[i])
}else{
newText.push(even[i])
newText.push(odd[i])
}
}
return decrypt(newText.join(""), n-1)
}