Top method for keeping track of most recent function outcome

Over time, I have become accustomed to utilizing the bind method to store the previous result of a function and keep track of it for future use. This allows me to easily concatenate or join the previous string with a new string without needing external variables:

function remStr(outStr){

  return function c(lastStr,newStr){

    if(!newStr) return lastStr;

    var all = lastStr+newStr;

    return c.bind(null,all);

  }.bind(null,outStr);

}

var str = remStr('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow

The issue arises when I need to call remStr multiple times, leading me to rely on bind. Is there a more efficient or alternative way to achieve the same outcome as remStr? Perhaps in certain scenarios, another approach may prove to be more effective than using remStr?

Answer №1

If I grasp your intention correctly, how about utilizing the concept of closure?

function concatenateString(baseStr) {
  return function add(newStr) {
    if (!newStr) return baseStr;
    baseStr += newStr;
    return add;
  }
}

var str = concatenateString('stack');
str = str('overflow');
str(); // stackoverflow

As pointed out by Tomalak in the comments, since JavaScript strings are immutable, it is advisable to buffer large or multiple strings in an array.

function concatenateString(baseStr) {
  var buffer = [baseStr || ''];
  return function add(newStr) {
    if (!newStr) return buffer.join('');
    buffer.push(newStr);
    return add;
  }
}

var str = concatenateString('stack');
str = str('over');
str = str('flow');
str(); // stackoverflow

Answer №2

Avoid using Function.bind in this situation. Instead, store the arguments in a cache and then concatenate them.

This technique is well known as functions can also act as objects and have properties. Using Function.bind alters the function's context, which is not necessary here.

function merge(word){
   return function combine(newWord){
       if(!newWord) return combine.words.join("");
       (combine.words || (combine.words = [word])).push(newWord);
   }
}

You can now utilize it as shown below:

var result = merge("mash");
result("up");
result("potatoes");
console.log(result()); // "mashuppotatoes"

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

A collapsible select list with checkboxes for children items

I am currently developing a website using Vue.js, HTML, and SCSS. I am looking to implement a drop-down functionality similar to the animated example provided in the gif below: https://i.stack.imgur.com/Mia2D.gif The gif demonstrates how the drop-down me ...

Angular Bootstrap uibModal is failing to resolve attributes

Issue with Roles in AngularJS Bootstrap uiModel var modalInstance = $uibModal.open({ animation: $scope.animationsEnabled, templateUrl: 'myModalContent.html', controller: 'ModalInstanceCtrl', size: 100, resolve: { roles: f ...

Is it possible to store Socket.IO responses in a cache for quicker retrieval?

Consider this scenario where I have a websocket implementation shown below: let itemsArray = []; function fetchData() { itemsArray = await db.query(`SELECT * FROM Items`); } function emitData() { io.sockets.in("room_foo").emit("data", JSON.stringify ...

Form fields will not automatically populate with link parameters; the user must manually input the information

My form fetches data from the database using server-side code when the user inputs the "user_id" field. The User ID field is the primary field on the form, and when the user enters their user ID, all other fields retrieve the corresponding user data from t ...

Validate the checkbox with Vuelidate only when the specified property is set to true

I have a website login form where users may need to check a specific checkbox before logging in. Here is part of the Vue component code that handles this functionality: <script setup lang="ts"> import {ref, defineProps} from 'vue&a ...

What could be causing one of my images to not appear on my Gatsby page?

Hey there, I could use some help with this issue: Recently, I created a website using Gatsby.js and deployed it to my web server (which is running NGINX on Ubuntu 20.04). The site uses Gatsby Image for querying and displaying images, and everything seems t ...

What is the method for obtaining a dynamic route path within the pages directory in Next.js?

In my code, I have a special Layout component that compares routing queries and displays the appropriate layout based on the query. I'm looking to extend this functionality to handle dynamic routing scenarios, such as invoices/invoice-1. Currently, ...

How can I use AngularJS to initiate code to run after the view and controller have successfully synchronized a specific change?

I am currently using AJAX to load date ranges into a pair of SELECTs (managed with AngularJS ng-repeat), which are then transformed into a slider using jQuery UI's selectToUISlider. My concern is that selectToUISlider may behave unexpectedly if the SE ...

What is the alternative method in JavaScript for locating items instead of using indexOf?

I have a set of paths in an array. Some paths are classified as constants while others are labeled as dynamic. A constant path would be something like "/booking-success", whereas a dynamic path could be something like '/arrival/view/:job_or ...

Accordionify your jQuery with integrated YouTube and Soundcloud embedding

Right now, I am in the process of creating a page dedicated to upcoming music releases. Each release will have its own preview embedded from YouTube or Soundcloud. My goal is to organize these embeds into accordion panels with automatic start/stop function ...

Exploring the concept of recursive method calls in TypeScript

I am trying to call the filterArr method inside the filterArr itself. Here is my current implementation: function filterArr(array, search) { var result = []; array.forEach((a)=> { var temp = [], o = {}, ...

"An error message stating 'Express: The body is not defined when

I'm encountering an issue while trying to extract data from a post request using express. Despite creating the request in Postman, the req.body appears empty (console.log displays 'req {}'). I have attempted various solutions and consulted s ...

IE11/Edge exhibits slow performance with components that have large datasets exclusively

Take a moment to analyze the following code snippet: <GridBody Rows={rows} />. Let's say that in this scenario, rows.length could reach 2000 or more, with each array containing approximately 8 columns. I have encountered a performance bottleneck ...

Removing a row from a table seamlessly without the need to reload the page

I am having an issue with my page that displays a list of orders. When a user clicks on a button to delete a row from the table, it only removes the first row successfully. However, when attempting to delete the second or third row, it does not work. Can s ...

Mongoose virtual population allows you to fetch related fields

When attempting to utilize virtual populate between two models that I've created, the goal is to retrieve all reviews with the tour id and display them alongside the corresponding tour. This is achieved by using query findById() to specifically show o ...

Trouble with passing the function variable to setState efficiently

Although I haven't worked with React for a while, it seems like this issue is more related to plain JS. Here is the setState function that I am using: // click event on parent for performance reasons ``Component:`` const [active, setActive] = useSta ...

Is there a way to mock a keycloak API call for testing purposes during local development?

At my company, we utilize Keycloak for authentication integrated with LDAP to fetch a user object filled with corporate data. However, while working remotely from home, the need to authenticate on our corporate server every time I reload the app has become ...

Scrollbar in an HTML selection tag

Is there a way to add a scroll bar to an HTML select box without using JavaScript? Alternatively, is there a JavaScript library that can achieve this behavior? Also, I'm looking for a redesign of the interface where I have two select boxes and items ...

Utilize jQuery to append YQL output in JSON format to specific IDs in your code

I have a YQL output JSON string at this URL: Check out the YQL JSON here I encountered some other I am exploring why I am facing difficulties in extracting certain items from the returned JSON. For instance, when using jQuery to access the H1 tag within ...

Exploring Nextjs with server-side rendering and fetching data from

When utilizing the getServerSideProps function in Next.js to make a fetch request to my API, I encountered an issue where the origin header was coming back as undefined. This seems to be specific to requests made from the server in Next.js, as I am able ...