Encode an array of bytes into base64 and split lengthy lines in Javascript (golf code challenge)

This innovative JavaScript function is designed to efficiently convert an array of numbers (ranging from 0-255) into a base64-encoded string. It also includes a feature that breaks long lines, if needed:

function encode(data)
{
  var str = "";
  for (var i = 0; i < data.length; i++)
    str += String.fromCharCode(data[i]);

  return btoa(str).split(/(.{75})/).join("\n").replace(/\n+/g, "\n").trim();
}

Are you up for the challenge of achieving the same functionality with less code? Can you optimize it for faster performance? Feel free to take advantage of new language features in JavaScript for this task.

Answer №1

Here is an alternative method:

function convertToBase64(data)
{
    var str = String.fromCharCode.apply(null,data);
    return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

When minified, it's only 88 characters long:

function c(d){return btoa(String.fromCharCode.apply(d,d)).replace(/.{76}(?=.)/g,'$&\n')}

If you prefer trailing newlines, the function can be shortened to 85 characters:

function c(d){return btoa(String.fromCharCode.apply(d,d)).replace(/.{1,76}/g,'$&\n')}

Answer №2

Compatible with Firefox version 3.6.13:

function convertToBase64(data)
{
    var str = data.reduce(function(a,b){ return a+String.fromCharCode(b) },'');
    return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

Answer №3

Unable to test this in Firefox right now, but looking at it from a string manipulation perspective, there seems to be room for optimization. The current method involves creating a new string one character longer than the previous one for every byte, making it an O(N^2) operation. To improve efficiency and achieve near-linear time complexity, consider the following approaches:

  1. Build strings up to 57 characters in length (resulting in a 76-char Base64 output), then use btoa followed by adding the result to your output.

  2. Similar to #1, create an array of lines and utilize join to form the final output.

  3. Utilize map to generate an array of 1-character strings, followed by calling join.

Below is unverified code snippets for each approach:

function encode(data)
{
  var output = "";
  var str = "";
  for (var i = 0; i < data.length; i++)
  {
    str += String.fromCharCode(data[i]);
    if (str.length == 57 && i != data.length - 1)
    {
      output += btoa(str) + "\n";
      str = "";
    }
  }
  return output + btoa(str);
}

function encode(data)
{
  var output = [];
  var str = "";
  for (var i = 0; i < data.length; i++)
  {
    str += String.fromCharCode(data[i]);
    if (str.length == 57)
    {
      output[output.length] = btoa(str);
      str = "";
    }
  }
  if (str != "")
    output[output.length] = btoa(str);
  return output.join("\n");
}

function encode(data)
{
  var str = data.map(function (d) { return String.fromCharCode(d) }).join("");
  return btoa(str).replace(/.{76}(?=.)/g,'$&\n');
}

And here's a minified version of the last option with only 116 characters:

function e(b){return btoa(b.map(function(d){return
String.fromCharCode(d)}).join("")).replace(/.{76}(?=.)/g,'$&\n')}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for accessing the theme spacing unit in MUI 5?

In previous iterations of MUI, accessing the theme spacing unit was possible through theme.spacing.unit, with a default output of 8. However, this property has been removed in MUI 5. I am having trouble finding documentation on how to access the theme sp ...

Perform simple arithmetic operations between a number and a string using Angular within an HTML context

I'm stuck trying to find a straightforward solution to this problem. The array of objects I have contains two values: team.seed: number, team.placement: string In the team.placement, there are simple strings like 7 to indicate 7th place or something ...

Encountering an issue with a Discord bot causing it to malfunction and deviate from its intended

Initially, everything appears to be functioning properly with the bot. When I execute the ?listen command, it responds correctly with bot is collecting messages now.... However, the ?stop command does not seem to have any effect. Furthermore, when I try th ...

Crafting LayerGroups on the Fly with Leaflet

Dynamic Creation of LayerGroups: Is it Achievable? I am currently working on a web map showcasing the various tree species present in parks. My goal is to create a separate LayerGroup for each species so that users can toggle visibility using a LayerContro ...

Using PHP to insert information from a dropdown menu depending on the selection from another dropdown

Having an issue with a dropdown list that is dependent on another dropdown list when trying to insert data into the database. Looking for suggestions on how to resolve this. <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1 ...

Arranging Arrays in an Object by Date Using Vue and JavaScript

I am currently working with an Object Structure similar to this: { 1000: [{AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19:52:01.000000Z"},{AnnouncementCode: 1000, Name: 'foo', created_at: "2022-02-01T19 ...

Creating TypeScript models from a JSON response in React components

My Angular 2 application retrieves a JSON string, and I am looking to map its values to a model. According to my understanding, a TypeScript model file is used to assist in mapping an HTTP Get response to an object - in this case, a class named 'Custo ...

Is it possible to prevent a page from reloading upon form submission in Svelte Kit without using preventDefault?

Whenever a user performs an action, like logging in to the app, I want to show a toast message for a few seconds. The login form is located at /login/page.svelte, with database interaction handled by /login/page.server.js. A writable store is used to save ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

What is the best way to save a token value to a JavaScript file on my local storage

Hello, I am new to Nodejs and have implemented passportjs token-based authentication. When a user logs in, a token is provided for each user. Now, I want to perform certain operations based on the users who have token values. For example, if a user wants t ...

Using javascript and d3.js to display a set number of items on each line through printing

I'm currently working on a project that involves printing a specific number of rectangles per line using d3.js var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect") .attr("x", function(d,i){ return i*5}) ...

Optimal method for aggregating results from a search query across a collection of 100,000 documents

Assuming I have a collection with 100k documents structured like this: { { userName: "cary" time: 50 userId: 1 } { userName: "john" time: 40 userId: 1 } { userName: "bliss" time: 50 ...

Do overlay elements have to be positioned at the bottom of the HTML body every time?

As I delve into the world of JavaScript frameworks, one common trend I've noticed is that elements like dialogs, tooltips, and alerts usually appear at the end of the body tag. With my own implementation of these UI elements, I am determined to make ...

Conceal the .dropdown-backdrop from bootstrap using solely CSS styling techniques

Is there a way to hide the .dropdown-backdrop element from Bootstrap for a specific dropdown on a webpage using only CSS? I found a solution that involves Javascript, you can view it on JSFiddle here. However, I am hoping to achieve this without relying o ...

What could be causing the jQuery code to not function properly when the left or right keys are pressed during mousedown?

Explanation of HTML code: <div class="wrap"> </div> Description of JavaScript code: $(document).ready(function() { $("body").mousedown(function(event) { switch (event.which) { case 1: alert('hel ...

During the Jasmine test, an error was encountered when trying to call a factory function that includes both a local and another function. The error message displayed

I have a factory with two functions and two local methods. I have written a Jasmine test case in which I expect the local method updateDetails and the factory function SavePref.savePref to be called when SavePref.saveDetails(values, prop); is invoked, as s ...

Dynamic loading of XML data into a DIV when hovering over it

The main idea behind my project is quite simple. I have a grid of company logos extracted from an XML document using XSLT, each logo with its own unique link to the respective company profile. On the same page, I have a separate div that serves as a "prev ...

Establish an HttpOnly cookie using JavaScript

Is it possible to convert a non-HttpOnly cookie into an HttpOnly cookie using JavaScript? ...

Creating a dynamic input box with an add/remove button in each row using jQuery

Need help with a jQuery-based UI that allows users to dynamically add input boxes. The desired look is as follows: Default appearance: INPUT_BOX [ADD_BUTTON] [REMOVE_BUTTON] Clicking on the [Add_Button] should add another row like this, and so on: ...

Analyzing registration details stored in an array against user login credentials

With two buttons available - one for sign up and the other for log in, my goal is to gather input form values from the sign-up section into an array. Following this, I aim to compare the user input from the sign-up with that of the log-in, informing the us ...