function to draw a table row in JavaScript with eloquent and descriptive arguments

I came across this code in chapter 6 of a programming book called "Eloquent JavaScript". I am struggling to understand where the arguments for the function 'drawRow' are coming from. If the outer function drawTable was a method, it would make sense for it to pass an array along with the current index. However, since it is just an ordinary function, I am confused about where 'row' and 'rowNum' are being retrieved from.

function drawTable(rows) {
  var heights = rowHeights(rows);
  var widths = colWidths(rows);

  function drawLine(blocks, lineNo) {
    return blocks.map(function(block) {
      return block[lineNo];
    }).join(" ");
  }

  function drawRow(row, rowNum) {
    var blocks = row.map(function(cell, colNum) {
      return cell.draw(widths[colNum], heights[rowNum]);
    });
    return blocks[0].map(function(_, lineNo) {
      return drawLine(blocks, lineNo);
    }).join("\n");
  }

  return rows.map(drawRow).join("\n");
}

I would appreciate any insights or explanations provided by those who take the time to address this. Thank you!

Answer №1

As per the information provided on MDN's page about Array.prototype.map, the callback function used with map typically takes three arguments: currentValue, index, and the entire array. When using drawRow with rows.map, the row represents the currentValue, while rowNum indicates the index.

For a more straightforward illustration, consider the following:

var arr = ['x', 'y', 'z'];

function displayArray(value, index) {
    console.log(index + ' ' + value);
}

arr.map(displayArray);
// This will output:
// 0 x
// 1 y
// 2 z

Answer №2

When utilizing the map method, the provided callback function (drawRow in this scenario) is invoked with three parameters for each item in the array being processed:

  • the item itself
  • the index of the item
  • the entire array (which is not being utilized in this context)

Additionally, there is an option to specify an object as the context for this within the callback function.

Answer №3

Like mentioned by others, the map function invokes drawRow with the necessary values. To demonstrate how this works, let's craft a new function from scratch named MAP that also utilizes drawRow with the appropriate values:

function MAP (theArray, callback) {
    var returnArray = [];
    for (var i=0; i<theArray.length; i++) {

        var result = callback(theArray[i],i); // pay attention to this line

        returnArray.push(result);
    }
    return returnArray;
}

The MAP function above takes a function that we provide with two arguments, the value of an item from theArray (theArray[i]) and the index of the item (i).

Now, we can utilize MAP to handle the rows:

MAP(rows, drawRow).join("\n");

Keep in mind that the function drawRow will be passed as the variable callback to MAP and the array rows will be passed as the variable theArray. MAP will then invoke drawRow as previously described with two arguments.

The Array.map() method functions similarly, but it is implemented as a method of array objects rather than a standalone function.

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 renaming folders with files in node.js?

The current method is effective for renaming a single folder with no files, but it fails when trying to rename a folder containing one or more files. const handleRenameFile = () => { const oldPath = `./${directory}/${fileName}`; const newPath = ...

Can you save data entered by a user into a text file using JavaScript or a similar technology in HTML, without the need to send it to a server?

Is there a way to create a site where user data is inputted into an input box or form, and then that information is stored in a .txt file on the user's C drive without uploading it to a server first? I've been experimenting with various forms an ...

Can you explain the purpose of `import type {Node} from 'react';` and how it is used in the App component as: () => Node?

Executing the following command: npx react-native init AwesomeProject When reviewing the App.js file, I came across two lines that confuse me: import React from 'react'; import type {Node} from 'react'; // Line 1 import { SafeAreaVi ...

The completion event for Ajax and Json does not activate Google Maps

I'm currently facing an issue with my Google Maps functionality. Despite trying various solutions that involve hidden tabs, the problem persists. The trouble lies in the fact that my ajax function successfully posts and retrieves data, but fails to tr ...

What is the best library to utilize for uploading an Excel file in a React application?

As a beginner in JS and React, I have a simple question that I hope someone can help me with! I am trying to figure out how to upload an excel file using a form and then extract the data from the rows and columns. For example, I would like to calculate th ...

When using Vue with CSS3, placing an absolute positioned element within a relative wrapper can cause issues with maintaining the

Just starting out with Vue and diving into the world of CSS3! I'm currently working on a component that you can check out here: https://codesandbox.io/s/yjp674ppxj In essence, I have a ul element with relative positioning, followed by a series of di ...

Displaying Material UI Styles: A Challenge

Currently working on a website using Material-UI and React. Strangely, the styling applied through Material-UI's Hook API functions perfectly on codesandbox.io but fails to work when running locally. Notably, the border radius feature fails to update ...

Display a JSON object on a web browser

I am trying to display a JSON object on a web browser using HTML. The object is already in a text file and has been properly formatted for readability. My goal is to maintain the same formatting when displaying it on the browser. ...

Retrieve the script's location from the server prior to the initialization of Angular

Is there a way to dynamically add a script in the index.html page based on the application version? I have a controller that retrieves the app version and attempted to achieve this using AngularJS: var resourceLoader = angular.module('MyTabs&apo ...

Is it possible to make a div jump or bounce if it has a flex display?

I'm looking to add some interactive animation to an image inside a div when my mouse hovers over it. To better explain the issue I'm facing, I created a quick representation of what I want to achieve in the code below. My goal is to have the te ...

What is the right rendering strategy to use for shouldComponentUpdate in React?

Provide an exhaustive list of all props required for rendering shouldComponentUpdate(nextProps, nextState) { if (this.props.color !== nextProps.color) { return true; } if (this.state.count !== nextState.count) { return true; ...

jQuery for Cross-Site AJAX Communication: Enhancing Website Function

I currently have a jQuery plugin that performs numerous AJAX calls, mostly JSON data. I'm interested in finding the most efficient way to enable cross-site calls, where the URLs used in $.get and $.post are not from the same domain. While I've h ...

Retrieve the original state of a ReactJs button from the database

I am completely new to ReactJs and I have a question regarding how to set the initial state of a button component based on data from an SQL database. I am successfully retrieving the data using PHP and JSON, but I am struggling with setting the state corre ...

Launching a call to action through Ajax in Zend Framework triggers a redirect, but subsequent calls prove to be effective

I've encountered an intriguing issue that I'm hoping someone else has come across and resolved before. In this particular application, I have implemented a 'change my password' option for users. If a user forgets their password, they c ...

Comparing HTML5 Drag and Drop to jQuery UI Drag and Drop: What's the Difference

In the ever-evolving world of web development, what is the most effective method for creating a drag and drop builder in 2017? While this question has been posed in the past (as seen here), technology changes rapidly. Is HTML5 still the go-to option, or ha ...

I can't believe I already have 111 npm downloads!

Just two days back, I released my initial npm package which is a basic library used to trim and merge audio files. You can check it out here. What surprises me is that it has already garnered 111 downloads even though I haven't promoted it or provide ...

The React syntax is malfunctioning

componentDidMount() { const restaurants = Restaurant.all() restaurants.then( rests => { this.setState({ restaurants: rests }) }) } render() { const { restauran ...

What is the best way to insert distinct values into an array in mongoDB?

I have a table of likes, and within that table, there is an array called videoLikes. I want to store the userData of users who have liked the video. However, when I attempt to add an object with a userId field to that array, I end up with duplicate data. S ...

What is the best way to attach a jQuery UI event handler to a button that has been dynamically generated?

Currently, I have a jquery ui modal dialog box form that inserts items into a table. A specific column in the table contains a button which serves as a link to edit the particular row. My goal is to attach an event handler to this button so that when a use ...

What is the process for incorporating an animated gif into a scene?

I'm trying to incorporate an animated gif in three.js. What's the best way to do it? var materialTextured = new THREE.MeshBasicMaterial( { map: THREE.ImageUtils.loadTexture('images/pin.gif'), transparent: true, ...