Convert (encoding/decoding)

var
Convert = {}
Convert.ResponseTo = ConvertResponseTo;
function ConvertResponseTo( type, response ) // return [byte]
{
    var ret = [];

    switch ( type )
    {
    case "application/json":
        ret.push( JSON.stringify( response ) );
        break;

    case "text/csv":
        ret.push( ConvertResponseTo.ToCSV( response.results ) );
        break;
    }

    return ret;
}
ConvertResponseTo.ToCSV
=
function( results )
{
    var csv   = "";
    var n     = results.length;

    if ( 0 < n )
    {
        var first = results[0];
        var order = [];

        //  Write the headers to csv
        for ( const [key, value] of Object.entries(first) )
        {
            csv += '"' + HTMLEntities.Decode( key ) + '"' + ",";

            order.push( key );
        } 
        csv += '\n';

        //  Write each tuple as csv rows
        for ( var i=0; i < n; i++ )
        {
            var row = results[i];

            for ( const key in order )
            {
                value = row[order[key]];

                if ( value )
                {
                    csv += '"' + HTMLEntities.Decode( value ).replace( /"/g, '""' ) + '"' + ",";
                }
                else
                {
                    csv += '"' + value + '"' + ",";
                }
            }
            csv += '\n';
        }
    }
    return csv;
}