Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could possibly be causing this variation?

// returns '0102'
export const bufferToHex = (buffer: Buffer): string => {
  const bytes = new Uint8Array(buffer)
  const hex = []
  bytes.forEach(byte => hex.push(byte.toString(16).padStart(2, '0')))
  return hex.join('')
}

// returns '12'
export const bufferToHex = (buffer: Buffer): string => {
  const bytes = new Uint8Array(buffer)
  return bytes
    .map((byte) => byte.toString(16).padStart(2, '0'))
    .join('')
}

When calling with:

bufferToHex(Buffer.from([1, 2])

Can anyone shed light on why this is happening?

Answer №1

TypedArray.prototype.map() will generate a fresh TypedArray, not an Array. The callback strings you supply are automatically converted to numbers when they're inserted into the indices of the newly created Uint8Array by using the .map() technique.

If utilizing .map() is your preference, I recommend the following approach:

export const bufferToHex = (buffer: Buffer): string => {
  return Array.prototype.map.call(
    buffer,
    (byte) => byte.toString(16).padStart(2, '0')
  ).join('')
}

The usage of bytes declaration becomes superfluous since Buffer already supports Uint8Array.

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

Label dynamically generated from user input for radio button option

In my attempt to develop a radio group component, I encountered an issue where the value of one radio option needs to be dynamically set by an input serving as a label. While I have successfully created similar components before without React, integrating ...

Tips for showing all percentages on a Google PieChart

I'm currently encountering two issues. How can I ensure that the entire legend is visible below the graph? Sometimes, when the legend is too large, three dots are added at the end. Another problem I am facing involves pie charts. Is there a way to d ...

Exploring the Contrast between Using @import for Styles and js Import for Webpack Configuration

While delving into the source code of ant-design, I couldn't help but notice that each component has both an index.ts and a index.less file in the style folder. This got me thinking - why is JavaScript being used to manage dependencies here? What woul ...

JavaScript: Targeting elements by their tag name within a designated container

When working with PHP, it is possible to use the getElementsByTagName method on any DOM object. However, this concept does not seem to exist in JavaScript. For example, if we have a specific node stored in the variable detailsNode, attempting to use detai ...

Reload a tab on an ajax-enabled webpage

I am currently facing an issue with refreshing a tab instead of the entire page using Ajax. The specific tab in question involves deleting credit cards. When I select the credit card I want to delete and confirm, I use "window.location.reload();" to refres ...

What is the process for creating a new element and utilizing its reference to add child elements in React?

I've been struggling to create an HTML element in a parent component in React, and then access that component's div from a child component in order to add new elements to it. Despite multiple attempts, I can't seem to resolve the issue of p ...

Leveraging promises with node.js and couched/nano for asynchronous operations

Currently experimenting with the Q promises library in conjunction with couchDB and Nano. The code below is able to display messages in the console, however, it seems that the database is not being created as expected. var nano = require('nano') ...

using the ng2-accordion component in your Angular 2 project

I am having trouble with the angular-2 accordion I implemented. It is not functioning properly and throwing a 404 error. The issue seems to be related to a third-party plugin called "ng2-accordion." I have double-checked the path of the package and it is ...

What makes realtime web programming so fascinating?

Working as a web developer, I have successfully created various real-time collaborative services such as a chat platform by utilizing third-party tools like Redis and Pusher. These services offer straightforward APIs that enable me to establish bidirection ...

Is it recommended to run JavaScript functions obtained from REST APIs?

Our single page application is built on Angular 4 and we are able to change input fields based on customer requirements. All the business rules for adjusting these fields are coded in JavaScript, which runs on the Java Platform and delivers the output thro ...

What is the process behind Twitter's ability to quickly show my profile?

Scenario I was intrigued by the different loading times of Twitter's profile page based on how it is accessed: Clicking the profile link in the menu results in a 4-second load time with DOM and latest tweets loade ...

React: Using useState and useEffect to dynamically gather a real-time collection of 10 items

When I type a keystroke, I want to retrieve 10 usernames. Currently, I only get a username back if it exactly matches a username in the jsonplaceholder list. For example, if I type "Karia", nothing shows up until I type "Karianne". What I'm looking f ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

Updating a Texture Image in Three.js

I'm currently working on a minecraft texture editor using three.js, with a similar interface to this. My goal is to implement basic click-and-paint functionality, but I'm facing challenges in achieving this. I have textures for each face of every ...

Tips for managing errors when using .listen() in Express with Typescript

Currently in the process of transitioning my project to use Typescript. Previously, my code for launching Express in Node looked like this: server.listen(port, (error) => { if (error) throw error; console.info(`Ready on port ${port}`); }); However ...

Which interface needs to be extended by props in order to include the "slot" property?

Currently, I am implementing a slot system in React using TypeScript. However, I am encountering an issue where I am unable to locate an interface that includes slot as a property. As a result, my TypeScript checker is generating the following error: Pr ...

Angular JS: Extracting the header from a CSV file

Just getting started with angular JS and I have a question. I need to take a CSV file from the user as input and then send it to the controller when they click submit. <button class="btn btn-primary" type="submit" ng-click="Input(File)">Submit</ ...

How can I update jQuery CSS method on resize event?

Having trouble vertically centering a div inside the body? I've come up with a jQuery function that calculates the ideal margin-top value for achieving perfect vertical alignment. Here's how it works: Obtain container height, Get child height, ...

The div that scrolls gracefully within its boundaries

Currently, I am working on a task that involves a div containing images that need to be scrolled left and right. I have successfully implemented the scrolling functionality using jQuery. However, I now face the challenge of ensuring that the content stays ...

how to display ajax response in webpage using jQuery

I need to perform multiple ajax calls in a for loop, with each call returning a text/html response that needs to be printed. Here is the code I have implemented: function printBill(printBills, lastBillNo, type,taxType,outletId,date){ var printableObjects ...