skip to Main Content

I have a usecase wherein I am reading streaming data from server, and putting it into an array. So my approach is:

var points = str.split("n"); //split input based on new line character
var positions = new Float32Array();
for (let i = 0; i < points.length; i++) {
  var coords = points[i].split("_"); //split line into individual values separated by '_'
  for(let j=0; j < coords.length; j++) {
      var coord = parseFloat(coords[j]) // parse string to float
      positions.push(coord); // add to float array
  }
}

But this is not working. code execution just stops at ‘push’, and nothing happens after that.

Is Float32Array not correct data structure for this usecase?

2

Answers


  1. The error is happen because you’re not initialize the size of array. You can change that code to my recommendations.

    var points = str.split("n"); // split input based on new line character
    var totalCoords = points.length * points[0].split("_").length; // calculate total number of coordinates
    var positions = new Float32Array(totalCoords); // initialize Float32Array with the correct length
    
    var index = 0;
    for (let i = 0; i < points.length; i++) {
      var coords = points[i].split("_"); // split line into individual values separated by '_'
      for (let j = 0; j < coords.length; j++) {
        var coord = parseFloat(coords[j]); // parse string to float
        positions[index++] = coord; // assign to the correct index in Float32Array
      }
    }
    

    Or you can just simple change Float32Array to basic array.

    var points = str.split("n"); // split input based on new line character
    var tempArray = []; // initialize a basic array
    
    for (let i = 0; i < points.length; i++) {
      var coords = points[i].split("_"); // split line into individual values separated by '_'
      for (let j = 0; j < coords.length; j++) {
        var coord = parseFloat(coords[j]); // parse string to float
        tempArray.push(coord); // add to basic array
      }
    }
    
    Login or Signup to reply.
  2. Typed arrays don’t have a push method. Instead just populate a standard array and then pass that to the Float32Array constructor. You could also use some array methods here, like map and flatMap:

    // Example input
    const str = `12.0_0.5
    -2.25_8.5
    3.5_16.0`;
    
    const positions = new Float32Array(
        str.split("n").flatMap(point => point.split("_").map(Number))
    );
    console.log(positions);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search