Transforming an element into a buffer using JavaScript

Utilizing Plain JavaScript for Data Transfer in Web Workers

In my current project, I am avoiding the use of Node and sticking to plain JavaScript within the browser. One challenge I encountered is efficiently sending data to web workers. After some experimentation, I successfully created buffers from arrays as shown below:

// assume it contains integers
var numbers = new Int8Array(10); 

// works
const data = {buffer: numbers.buffer};
worker.postMessage(data, [data.buffer]);

Now, let's consider a scenario where I have an object structured like this:

var myObject = {'in': [0.123,-0,521], 'out' : [1.409]};

The question that arises is how can I convert this object into a buffer without relying on Node.js? I came across similar inquiries online, but most solutions involved using Node which is not part of my current setup.

Answer №1

To form a typed Array of values, you can follow this structure:

[obj1.in1,obj1.in2,obj1.out,obj2.in1,...]

If you have just one object:

var arr=Int8Array.from(myObject.in.concat(myObject.out));

In case you are dealing with an Array of objects:

var ObjArr=[obj1,obj2];
var arr=new Int8Array(ObjArr.length*3);

for(var i=0;i<ObjArr.length;i++){
  var obj=ObjArr[i];
  arr.set(obj.in.concat(obj.out),i*3);
}

You can iterate over the array using a simple for loop like so:

for(var i=0;i<arr.length-2;i+=3){
 var in1=arr[i],in2=arr[i+1],out=arr[i+2];
 ...
}

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

Display a dynamic variable within React's HTML code

const fetchTime = () => { const currentDate = new Date(); const currentTime = currentDate + ' ' + currentDate.getHours() + ":" + currentDate.getMinutes() + ":" + currentDate.getSeconds(); return {currentTime}; } export default fun ...

The modal remains visible

Has anyone encountered a problem with hiding a Bootstrap modal based on form validation in JavaScript? I'm facing an issue where the submit function is not executed when I click the button. I've attempted using onsubmit=validateForm(), but it doe ...

Tips for implementing a JavaScript Material Design framework in ReScript code?

I am attempting to integrate the material-ui library into a Rescript/React application. The code snippet below demonstrates how to display a button: @module("@material-ui/core/Button") external button: string = "default" @react.compone ...

Attempting to access the 'name' field from an input element in an HTML document using AngularJS, and also introducing a static field named 'likes' with a value

Currently, I am in the process of developing an application that retrieves a list of Beers from an API. Each beer in the JSON response contains the fields {name: "beer", id: number, likes: number}. However, I am facing a challenge while attempting to add ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

JavaScript Ping Pong Challenge

I'm currently investigating why the browser returns NaN for the Positions. The game is being rendered in a loop and updated as soon as the monitor is ready, which is defined in the update() function and runs infinitely. The reset() function is a part ...

What could be causing my jQuery switch not to function on the second page of a table in my Laravel project?

Having an issue with a button that is supposed to change the status value of a db column. It seems to only work for the first 10 rows in the table and stops functioning on the 2nd page. I'm new and could really use some help with this. Here's the ...

Issue encountered during rootScope update

I've encountered an issue with my Angular service that updates the $rootScope. The actual updating process works as intended, but it triggers an error in the console that has me concerned. app.service("scroll", function($rootScope, $window) { this ...

What is the best way to utilize AJAX to send a value from a foreach loop in Laravel?

I'm encountering an issue where all forms are sending the value as if it's from the first form, however, my intention is for each form to send the data inside it when I press the send button. Blade @foreach($car_lists as $car_list) <li class= ...

Encountering a CORS policy error in Three.js when attempting to run locally

I'm just starting out on this website and I'm eager to dive into learning javascript. My initial attempt at following this example from resulted in an error without any animation or background showing up. Instead, all I see is a photo displayin ...

What is the best way to tally data-ids within an anchor tag using jQuery or plain JavaScript?

find total number of data-id attributes within tag a I am looking for a way to calculate the count of my id attribute, whether it is in data-id or another form, using JavaScript. Edit ...

Establish a timeout for the Material UI drawer to close automatically after being opened

I am looking for a way to automatically close the drawer after a specific duration, but it seems that material UI drawer does not have the necessary props for this. Is there a workaround using transitionDuration or perhaps adding a setTimeout in my functio ...

Troubleshooting: Issue with Displaying $Http JSON Response in AngularJS View

Struggling to retrieve JSON data from an API and display it in a view using AngularJS. Although I am able to fetch the data correctly, I am facing difficulties in showing it in the view. Whenever I try to access the object's data, I constantly receive ...

Trigger an event in Angular using TypeScript when a key is pressed

Is it possible to activate a function when the user presses the / key in Angular directly from the keydown event? <div (keydown.\)="alerting()"> </div> <div (keydown.+)="alerting()"> </div> Both of these ...

Is there a way to conceal the article container?

My experience with javascript and Mapbox is still limited, so please bear with me. I am currently working on a map that showcases various restaurants in NYC and their impact during the recession. Additionally, I am trying to include small columns for artic ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

An intriguing inquiry regarding HTML form intricacies

Looking to enhance the source code by adding a new column to display Client Mobile, Client Office Telephone, and Client E-mail in a separate popup PHP page. My attempt involved adding a form and submit button to generate the new column. However, pressing ...

Testing the Mongoose save() method by mocking it in an integration test

I am currently facing an issue while trying to create a test scenario. The problem arises with the endpoint I have for a REST-API: Post represents a Mongoose model. router.post('/addPost', (req, res) => { const post = new Post(req.body); ...

A guide on extracting split values and assigning them to individual variables

Currently, I'm working on a project utilizing node.js, express, mongo, and socket.io. After successfully retrieving geolocation coordinates and storing them in a hidden input field, I encountered an issue when attempting to save the data into the data ...

What steps should I take to incorporate this feature into my Meteor project?

After successfully installing the type.js package, I discovered that the code works fine when directly executed in the console. Here is the code snippet: $(function(){ $(".typedelement").typed({ strings: ["You don&apo ...