Search code examples
clojurescript

How do I get data out of a Uint8Array in ClojureScript?


I am getting a MIDI message from a midiAccess object as an Uint8Array in a ClojureScript site but I can't seem to convert it to something I can get values from. (js/console.log message) generates Uint8Array(3) [128, 65, 0] in the browser console. Actually, 'first' on the message gets the first value, but then 'second' does not. Using js->clj doesn't seem to convert it into anything usable. How do I wrangle the data out of it? I tried js->clj but that seemed to keep it the same.


Solution

  • Here are some examples:

    (let [ui8a (Uint8Array.from [0 1 2 3 4 5])]
    

    then

    ui8a              => #object[Uint8Array 0,1,2,3,4,5]
    
    (.-length ui8a)   => 6
    (first ui8a)      => 0
    (second ui8a)     => 1
    (aget ui8a 3)     => 3
    
    (into [] ui8a)    => [0 1 2 3 4 5]  ; either one works
    (vec ui8a)        => [0 1 2 3 4 5]
    

    You may find this list of documentation sources helpful. Be especially sure to study the Clojure CheatSheet daily!