1+ ( function ( ) {
2+ const aluraKeys = {
3+ 'e' : 'enter' ,
4+ 'i' : 'imes' ,
5+ 'a' : 'ai' ,
6+ 'o' : 'ober' ,
7+ 'u' : 'ufat' ,
8+ } ;
9+
10+ function cipher ( str , dict ) {
11+ const regex = new RegExp ( Object . keys ( dict ) . join ( '|' ) , 'gi' ) ;
12+ return str . replace ( regex , ( match ) => dict [ match ] ) ;
13+ }
14+
15+ function decipher ( str , dict ) {
16+ const regex = new RegExp ( Object . values ( dict ) . join ( '|' ) , 'gi' ) ;
17+ return str . replace ( regex , ( match ) => Object . keys ( dict ) . find ( key => dict [ key ] === match ) ) ;
18+ }
19+
20+ function classManagerOutput ( toRemove , toAdd , className ) {
21+ toRemove . classList . remove ( className ) ;
22+ toAdd . classList . add ( className ) ;
23+ }
24+
25+ function ButtonManager ( state ) {
26+ const xButtons = document . querySelectorAll ( '.input-text-btns div button' ) ;
27+ if ( state === 'add' ) {
28+ xButtons . forEach ( button => button . setAttribute ( 'disabled' , true ) ) ;
29+ } else if ( state === 'remove' ) {
30+ xButtons . forEach ( button => button . removeAttribute ( 'disabled' ) ) ;
31+ }
32+ }
33+
34+ function validateText ( e ) {
35+ const regex = new RegExp ( '[A-ZÀ-ú]' , 'g' ) ;
36+ if ( regex . test ( e . target . value ) ) {
37+ ButtonManager ( 'add' ) ;
38+ }
39+ else {
40+ ButtonManager ( 'remove' ) ;
41+ }
42+ }
43+
44+ function cleanTextArea ( element ) {
45+ element . value = '' ;
46+ }
47+
48+ window . onload = ( ) => {
49+ //DOM
50+
51+ //Buttons
52+ const cryptBtn = document . getElementById ( 'crypt-btn' ) ;
53+ const decryptBtn = document . getElementById ( 'decrypt-btn' ) ;
54+ const copyBtn = document . getElementById ( 'copy-btn' ) ;
55+ //Text Areas
56+ const textToManipulate = document . getElementById ( 'text-to-manipulate' ) ;
57+ const outputText = document . getElementById ( 'output-text' ) ;
58+ //
59+ const text = document . getElementById ( 'text' ) ;
60+ const noText = document . getElementById ( 'no-text' ) ;
61+
62+ //Events
63+
64+ textToManipulate . addEventListener ( 'input' , validateText ) ;
65+ textToManipulate . addEventListener ( 'paste' , validateText ) ;
66+
67+ cryptBtn . addEventListener ( 'click' , ( ) => {
68+ if ( textToManipulate . value . length > 0 ) {
69+ let result = cipher ( textToManipulate . value , aluraKeys ) ;
70+ classManagerOutput ( text , noText , 'hidden' ) ;
71+ outputText . value = result ;
72+ cleanTextArea ( textToManipulate ) ;
73+ }
74+ } ) ;
75+
76+ decryptBtn . addEventListener ( 'click' , ( ) => {
77+ if ( textToManipulate . value . length > 0 ) {
78+ let result = decipher ( textToManipulate . value , aluraKeys ) ;
79+ classManagerOutput ( text , noText , 'hidden' ) ;
80+ outputText . value = result ;
81+ cleanTextArea ( textToManipulate ) ;
82+ }
83+ } ) ;
84+
85+ copyBtn . addEventListener ( 'click' , ( ) => {
86+ outputText . select ( ) ;
87+ document . execCommand ( 'copy' ) ;
88+ } ) ;
89+ }
90+ } ) ( )
0 commit comments