File tree 2 files changed +75
-0
lines changed
2 files changed +75
-0
lines changed Original file line number Diff line number Diff line change
1
+ const { checkAnagrams } = require ( '.' ) ;
2
+
3
+ describe ( 'Anagrams' , ( ) => {
4
+ it ( 'Should return TRUE for `rail safety` & `fairy tales`' , ( ) => {
5
+ expect (
6
+ checkAnagrams ( {
7
+ firstString : 'rail safety' ,
8
+ secondString : 'fairy tales' ,
9
+ } ) ,
10
+ ) . toBe ( true ) ;
11
+ } ) ;
12
+
13
+ it ( 'Should return TRUE for `FAIRY tales` & `rail SAFETY`' , ( ) => {
14
+ expect (
15
+ checkAnagrams ( {
16
+ firstString : 'FAIRY tales' ,
17
+ secondString : 'rail SAFETY' ,
18
+ } ) ,
19
+ ) . toBe ( true ) ;
20
+ } ) ;
21
+
22
+ it ( 'Should return FALSE for `Hello World` & `Bye`' , ( ) => {
23
+ expect (
24
+ checkAnagrams ( {
25
+ firstString : 'Hello World' ,
26
+ secondString : 'Bye' ,
27
+ } ) ,
28
+ ) . toBe ( false ) ;
29
+ } ) ;
30
+
31
+ it ( 'Should ignore special characters' , ( ) => {
32
+ expect (
33
+ checkAnagrams ( {
34
+ firstString : 'hello world!!' ,
35
+ secondString : 'hello - world' ,
36
+ } ) ,
37
+ ) . toBe ( true ) ;
38
+ } ) ;
39
+ } ) ;
Original file line number Diff line number Diff line change
1
+ function createCharMap ( str ) {
2
+ const charMap = { } ;
3
+ const sanitizedString = str . replace ( / [ ^ \w ] / g, '' ) . toLowerCase ( ) ;
4
+ sanitizedString . split ( '' ) . forEach ( ( char ) => {
5
+ if ( ! charMap [ char ] ) {
6
+ charMap [ char ] = 1 ;
7
+ } else {
8
+ charMap [ char ] += 1 ;
9
+ }
10
+ return 0 ;
11
+ } ) ;
12
+ return charMap ;
13
+ }
14
+
15
+ function checkAnagrams ( { firstString, secondString } ) {
16
+ const charMapFirst = createCharMap ( firstString ) ;
17
+ const charMapSecond = createCharMap ( secondString ) ;
18
+
19
+ if ( Object . keys ( charMapFirst ) . length !== Object . keys ( charMapSecond ) . length ) {
20
+ return false ;
21
+ }
22
+
23
+ // eslint-disable-next-line no-restricted-syntax
24
+ for ( const char in charMapFirst ) {
25
+ if ( charMapFirst [ char ] !== charMapSecond [ char ] ) {
26
+ return false ;
27
+ }
28
+ }
29
+
30
+ return true ;
31
+ }
32
+
33
+ module . exports = {
34
+ checkAnagrams,
35
+ createCharMap,
36
+ } ;
You can’t perform that action at this time.
0 commit comments