R switch between point of segment and points of square in Hilberts Curve

Happy new year! Below I have my code in R which creates the Hilber curve of the 1st chromosome from a Bam file.

library(chromstaR)
library(GenomicRanges)
library(HilbertCurve)
library(circlize)
bampath <-"C:/Users/User/Documents/R/win-library/4.0/GenomicRanges/extdata/wgEncodeUwRepliSeqBg02esG1bAlnRep1.bam"
bam <- bampath

reads <- readBamFileAsGRanges(bam, chromosomes='chr1', pairedEndReads=FALSE,
                              min.mapq=10, remove.duplicate.reads=TRUE)

hc = GenomicHilbertCurve(chr = "chr1", level = 5)
hc_points(hc, reads, gp = gpar(col = "blue")) 

Now what I want to create is the following. I want from a point of a segment to find the coordinates in the Hilbert curve and the opposite i.e from a coordinate from the Hilbert Curve to find the point in the line segment.

I found from the web the following solution but is in js.

function hilbertMap(quadits) {
        if ( quadits.length === 0 ) {
            return new Point(0, 0);
        } else {
            return (function() {
                var pt, t, x, y;
                t = quadits.shift();
                pt = hilbertMap(quadits);
                x = pt.x;
                y = pt.y;
                switch(t) {
                    case 0: 
                        return new Point(y * 0.5 + 0, x * 0.5 + 0);
                    case 1:
                        return new Point(x * 0.5 + 0, y * 0.5 + 0.5);
                    case 2:
                        return new Point(x * 0.5 + 0.5, y * 0.5 + 0.5);
                    case 3:
                        return new Point(y * -0.5 + 1.0, x * -0.5 + 0.5);
                }
            })();
        }   
    }
    
    
    function hilbertMapInverse(x, y, depth) {
        var t;
        if ( depth > 1 ) {
            return 0;
        }
        else {
            if ( x < 0.5 ) {
                if ( y < 0.5 ) {
                    return (hilbertMapInverse(y * 2, x * 2, depth * 4) + 0) / 4;
                }
                else {
                    return (hilbertMapInverse(x * 2, y * 2 - 1, depth * 4) + 1) / 4;
                }
            }
            else {
                if ( y >= 0.5 ) {
                    return (hilbertMapInverse(x * 2 - 1, y * 2 - 1, depth * 4) + 2) / 4;
                }
                else {
                    return (hilbertMapInverse(1 - y * 2, 2 - x * 2, depth * 4) + 3) / 4;
                }
            }
        }
    }



})();

Please in need help to transform in R the code in js and to attach on my Hilbert curve. Thank you