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

Multiple button clicks causing events to fire repeatedly

My PHP file echoes a button, but when I click it, the action fires multiple times. Why is it behaving like this? I have tried solutions from Stack Overflow, but none of them seem to work. Any suggestions or corrections? $(document).on('click',& ...

Track the number of views each month using PHP and MySQL to generate dynamic jQuery charts

I am currently utilizing jQuery with chart.js to display the view counter based on month using PHP and MySql. Each page view is inserted into MySql in the following format : | id | ip | page | date(timestamp) | | 1 | 138.86.20.20 | test.p ...

Searching for the desktop location using Node.js

As discussed in the Node.js - Find home directory in a platform-agnostic way question, we can locate the home directory using the following code: const homedir = require('os').homedir(); However, how can I locate the desktop folder in Windows r ...

Creating a dynamic object with JavaScript using two arrays

Can anyone assist me in constructing an array of objects by combining data from two different arrays? const parent =[ { Id: 1, Cate: 'Accommodation', p_id: null }, { Id: 4, Cate: 'National Travel', p_id: null } ] const child =[ { ...

Is it possible to trim a video using HTML code?

I am trying to find a way to crop a video using HTML 5. <video id="glass" width="640" height="360" autoplay> <source src="invisible-glass-fill.mp4" type="video/mp4"> </video> Currently, the video has a resolution of 640x360. However ...

A guide on using FileReader to efficiently read multiple images

I need to be able to select multiple images from one input and read them using File Reader. If I leave it as is, it only gives me one picture. const [image , setImage] = useState(''); const [imageSelected , setImageSelected] = useState(nul ...

What is the best way to transition a connected component from a class-based to a functional component in TypeScript?

I'm in the process of switching from a class-based component to a functional component. This is a connected component that uses mapState. Here is my initial setup: import { connect } from 'react-redux' import { fetchArticles } from '. ...

What is the best way to display multiple values in a single column in a datatable?

This function works effectively in rendering the code: { "data": "assignedTo", "render": function (data) { var btnDetail = "<a href='/Ticket/TicketDetail?ticketI ...

Using regex, match any word along with the preserved white space and consider parentheses as a single word

I need help with creating a regex pattern to split a string of words in a specific way. The current pattern I've been using is (?!\(.*)\s(?![^(]*?\)), but it's not giving me the desired outcome. It's close, but not quite the ...

Here's how you can use welding techniques to attach objects and incorporate fin-like structures in THREE

I am currently working on a project involving a rocket ship orbiting various planets. To achieve this, I have started by creating my own rocket ship object and am aiming to model it similarly to this design: https://kyleagnew.files.wordpress.com/2018/02/lo ...

unable to display picture on puggy

Check out the code snippet below: <!DOCTYPE html> <html lang="en> <head> <meta charset="UTF-8> <title>Home Page</title> </head> <body> <img src="resources/mainlogo.png" style="width:304px;height:2 ...

Eliminating choices from a dropdown list using jQuery

I am currently working on a page that contains 5 dropdown menus, all of which have been assigned the class name 'ct'. During an onclick event, I want to remove the option with the value 'X' from each dropdown menu. My current code snipp ...

Is the max and min-width being properly set by the keen-slider__slide class in keen-slider?

Check out my code snippet below: import React from 'react' import { useKeenSlider } from 'keen-slider/react' // Styles import 'keen-slider/keen-slider.min.css' interface Props { children: any } // const animation = { du ...

Using the Match() function with an array of objects

I am working with an object array containing multiple variables. let Novels = []; class Novel { constructor(isbn, title, author, edition, publication, year) { this.isbn = isbn; this.title = title; this.author = author; this.publicat ...

Tips for querying orchestrate.io

Recently, I found myself in need of a user-friendly database for a small highscore system in my game development projects using JavaScript. Through the Github student developer pack, I came across Orchestrate.io. After discovering a suitable driver module ...

The AJAX status is now 0, with a ready state of 4

Struggling to execute an AJAX call (using only JavaScript) to store a user in the database. The JavaScript file I am working with includes this code: var url = "interfata_db.php"; xmlhttp.onreadystatechange = function(){ alert('ready state &apos ...

"Converting jQuery Form into a Wizard feature with the ability to hide specific steps

I'm working on a form where I need to hide a fieldset when a specific event is triggered. Inside the first fieldset, there is a select tag and when a certain option is selected, the second fieldset should be hidden. <form id="form1"> <fi ...

Custom HTML binding in expanding rows of Angular 2 DataTables

I am currently working on implementing a data table feature that allows for an extended child row to be displayed when clicking the + icon. This row will show additional data along with some buttons that are bound via AJAX before transitioning to Angular 2 ...

Ways to maneuver the vehicle by using the left or right key inputs

I am a beginner with canvas and game development. I am currently working on a project where a car moves in a straight line, but I want to add functionality for the car to turn anti-clockwise when the left key is pressed, and clockwise when the right key is ...

Ways to reduce the amount of time spent watching anime when it is not in view

My anime experiences glitches as the black container crosses the red, causing a decrease in duration. Is there a way to fix this glitch? I attempted to delay the changes until the red path is completed, but the glitches persist. delayInAnimeSub = ourVilla ...