What is the best way to make TypeScript's Array.map() function return the same results as in VanillaJS?

For my Angular6 App project, I am currently working on implementing Conway's Game of Life. My goal is to create a two-dimensional array of class instances with dimensions n x m. In vanillaJS, I managed to achieve this using the following code snippet:

generateInitialState(bias) {
    return [...Array(this.rows)]
        .map((a, i) => [...Array(this.columns)]
            .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}

This code snippet generates an Array with a length equal to this.rows, which contains Arrays filled with n (this.columns) instances of the Cell class. For example, when this.rows = this.columns = 4 (output from console):

[ [ Cell { x: 0, y: 0, state: 'alive' },
        Cell { x: 1, y: 0, state: 'dead' },
        Cell { x: 2, y: 0, state: 'alive' },
        Cell { x: 3, y: 0, state: 'dead' } ],
      [ Cell { x: 0, y: 1, state: 'alive' },
        Cell { x: 1, y: 1, state: 'alive' },
        Cell { x: 2, y: 1, state: 'dead' },
        Cell { x: 3, y: 1, state: 'dead' } ],
      [ Cell { x: 0, y: 2, state: 'alive' },
        Cell { x: 1, y: 2, state: 'alive' },
        Cell { x: 2, y: 2, state: 'alive' },
        Cell { x: 3, y: 2, state: 'dead' } ],
      [ Cell { x: 0, y: 3, state: 'dead' },
        Cell { x: 1, y: 3, state: 'alive' },
        Cell { x: 2, y: 3, state: 'alive' },
        Cell { x: 3, y: 3, state: 'alive' } ] ] 

The above logic functions correctly in vanillaJS and generates the Array as expected. However, when translating the code to TypeScript, it only returns an empty array with a length equal to this.rows. The TypeScript equivalent appears to compile down to:

function generateInitialState(bias) {
var _this = this;
return Array(this.rows).slice().map(function (a, i) { return Array(_this.columns).slice().map(function (b, j) { return new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'); }); });
}

How can I modify the TypeScript implementation to function properly?

Full Code

class Game {
  constructor(columns, rows, randomBias){
    this.columns = columns; 
    this.rows = rows;
    this.randomBias = randomBias;
    this.cells = this.generateInitialState(this.randomBias);
  }
  /* Content omitted for brevity */
  generateInitialState(bias) {
    return [...Array(this.rows)]
      .map((a, i) => [...Array(this.columns)]
        .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
  }
}
class Cell{
  constructor(x, y, state){
    this.x = x;
    this.y = y;
    this.state = state;
  }
}
let a = new Game(4, 4, 0.5);
console.log(a.cells);

Answer №1

The issue lies in the method of initializing an array with a specific size. When you use this code:

[...Array(this.rows)]

it actually compiles to

Array(this.rows).slice()</coode>, resulting in no values being produced because the array contains "holes" instead of filled with <code>undefined
values like in the original (uncompiled) version. These holes are not recognized by map.

To resolve this, try using

Array.from({ length: this.rows })
instead:

function generateInitialState(bias) {
  return Array.from({ length: this.rows })
    .map((a, i) => Array.from({ length: this.columns })
      .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}

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 an alert message only the first time a checkbox is checked

I have a checkbox that, when checked, triggers an alert asking if the user is sure. Upon agreement, all exercises are marked as done. The problem: I use local storage to save an item called didAllExercises. When reopening the app, if this item is true, th ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

Can the "try" function be utilized within an "if" statement?

Within my program lies a 2D array: Test=[ ["TestName", "123", "1", "2.5"], ["NameTest", "321", "10", "5.2"], ["jpoj", "321", "10", "5.2 ...

Errors in JavaScript are displayed when a React application is built for production

I have developed a client react application using create-react-app. It communicates with a node server that runs an express api. During development, everything was smooth sailing and I was preparing for deployment. After running npm run build, there were ...

Utilizing Angular 7 to extract data from the initial column of an Excel spreadsheet and store it within an array

Currently, I am in the process of uploading an excel file that contains an ID column as its first column. My goal is to extract all the IDs and store them in an array for future data management purposes. To accomplish this task, I am utilizing the XLSX l ...

How to Update a Nested Document in Mongoose

I am currently working on a polls application using angular, express, and mongoose. Here is an overview of my data structure: var mongoose = require('mongoose'); var responseSchema = new mongoose.Schema({ responseText: String, votes: { ...

When trying to access Ajax fetched data within a VueJS `router-view`, the `$root` object returns undefined only when navigating directly to

As I familiarize myself with vuejs, I decided to challenge myself by creating a webpage similar to an eshop for practice purposes. My approach involves fetching all the necessary data in a single api call to ensure easy access from all my router-views for ...

A comprehensive guide on implementing Three.InstancedMesh in Aframe

Currently, my project is focused on incorporating instancing in Aframe using the ThreeJs InstancedMesh. I'm following the example provided in this link: https://github.com/mrdoob/three.js/blob/master/examples/webgl_instancing_dynamic.html Highlighted ...

Does the server transmit HTML page content rather than the information you need?

My React application is connected to a backend built with Node.js. However, when I try to fetch data in my React component, the server sends back an HTML page instead of the expected data, displaying raw HTML on the screen. Backend (server.js): app.route ...

Tips on sending an array to material-ui dataSource props

Currently utilizing material-ui for a component. I am facing an issue with the autocomplete component in material-ui where I intend to display a list of icon names along with the icons. When only passing MenuItem to dataSource, it results in an empty input ...

It appears that Jest is having trouble comprehending the concept of "import type"

We've just completed a major update to our monorepository, bringing it up to date with the following versions: Nx 14.3.6 Angular 14.0.3 Jest 28.1.1 TypeScript 4.7.4 Although the compilation process went smoothly after the upgrade, we encountered num ...

What is the best way to deactivate div elements once an overlay has been applied to them?

My goal is to place an overlay on my form to prevent users from accessing the content. Even though I have added an overlay, users can still interact with input fields. How can I prevent that? .overlay { background: rgba(0, 0, 0, .75); text-align: ce ...

Changing variables from a different file in node.js: a guide

Currently utilizing the discord.js library for my project. Although I can refer to it as such, I am encountering issues when trying to access certain files. For example, let's consider a file named calc.js. In this scenario, I aim to retrieve a var ...

What is the best approach for capturing and managing a 406 error in VUEJS?

I am encountering a situation where I send the day and time to the API in order to verify if there is an opening in the schedule stored in the database. If no opening is found, the API responds with a 406 error code. As a result, I am seeing a 406 error ...

Accessing Nested Arrays in Angular 8: Retrieving Data in HTML Template from Multiple Layers of Arrays

Hello there. I'm using an API that gives me the following data: (4) [{…}, {…}, {…}, {…}] 0: dueDate: "2018-03-26T00:00:00" priority: {priorityId: 1, priorityName: "Critical", priorityColor: "red"} statuses: Array(1) 0: ...

``The problem of cross-origin resource sharing (CORS)

Encountering a CORS error when sending the request, although it works fine in Postman Error Message: The fetch request to (cloud function url) from my web app origin is being blocked by CORS policy: No 'Access-Control-Allow-Origin' header is p ...

Is there a way I can inform iPhone users on my webpage about the existence of an app?

Hey there! I've managed to figure out how to detect the platform being used. It's working well so far: // Extract User-Agent String var UserAgent = navigator.userAgent.toLowerCase(); // Check User-Agent for certain keywords if (UserAgent.search ...

Is it possible to alter HTML content dynamically by searching with JavaScript?

When I utilize a search function to find contact information for individuals, initially there are four contacts listed: 1)"Jonathan Buell", 5804337551, "family" 2)"Patrick Daniel", 8186934432, "work" 3) "Lorraine Winter", 3138211928, "work" 4) "Constan ...

How does a browser decide to load content from an http URL when the frontend source is using an https URL?

When using my Vue component to load external content in an iframe, everything works fine locally. However, once I deploy it to my HTTPS site, I encounter an issue. <iframe src="https://external-site" /> Upon deployment, I receive the following erro ...

Typescript code pointing to a specific file location

MainDirectory |_bin |_config |_source > myfile.ts I am currently learning about typescript and I am trying to reference a file located in a different folder. Specifically, I have created a new folder called Folder1 within the config directory, which co ...