DEV Community

hk7math
hk7math

Posted on • Edited on

JavaScript CPU Emulator Problem

I've picked up CodeSignal again and aim to solve something every day (either challenges or casual problems). Recently, we got a medium challenge from hamlet_m1. It is to emulate a CPU assembly language. (Hope I didn't mix up technical terms).

This time, I'm proud to be one of the JS solvers together with other 8 geeks:

User Level Country Chars
Thomasz 70 USA 290
Giang_P_r 87 Vietnam 437
kov 93 Hungary 480
hk7math 44 Hong Kong 503
danielhong35 86 USA 512
murtaza_m2 43 Romania 921
omar-aguilar 62 Mexico 1367
linh_pv_9x 82 Vietnam 1490
jonathas_s1 24 Brazil 2198

The best solution by thomasz is an awe to me! Not only is it far shorter than all other solutions, but it is also still highly readable (to people like me who like hacky tricks)

Disclaimer: the full solution just for reference, please tell me to delete it if I violated any rule...

cpuEmulator = s => {

    z = 2 ** 32
    r = Array( 43 ).fill( 0 )
    R = x => +x.split`R`[ 1 ]

    for ( d = 0; l = s[ d++ ]; ) {

        [ c, a, b ] = l.split(/[\s,]/)
        o = y => r[ R( a ) ] = ( r[ R( a ) ] + y + z ) % z

        c == 'MOV' ?
            r[ R( b ) ] = R( a ) + 1 ? r[ R( a ) ] : +a  :            
        c == 'ADD' ?
            o( r[ R( b ) ] ) :
        c == 'DEC' ?
            o( -1 ) :
        c == 'INC' ?
            o( 1 ) :
        c == 'INV' ?
            o( ~r[ R( a ) ] * 2 + 1 ) :
        c == 'JMP' || c == 'JZ' && !r[ 0 ] ?
            d = +a - 1 : 0       
    }

    return r[ 42 ] + ''
}
Enter fullscreen mode Exit fullscreen mode

Here are some tricks I discovered in this snippet:

  1. Array(n).fill(x) to initialize an array of length n with prefilled values x (be careful about multi-dimension arrays though)
  2. +'numeric string' to cast a string as a number or NaN
  3. Regex /[xyz]/ to split string by separators x, y, z simultaneously
  4. c == 'case1' ? ... : c == 'case2' ? ... : ... to well format nested ternary operators as a switch-case
  5. number + '' to cast a number as a string

Feel free to drop a comment about your takeaways :D

Top comments (0)