If the first returned function of the compose function is called without any arguments, what is the starting value of its reduce function?

In my attempts to modify the compose function to output to the console using different arguments, I am struggling to find a solution. The initial call of the compose function results in an undefined argument arg. Consequently, the reduce function utilizes the first element of the array (console.clear()) as the starting value, which is then passed as the argument for the subsequent function, getCurrentTime.

When compose is invoked with convertToCivilianTime, it takes the output from serializeClockTime and passes it as the parameter for the first returned function in compose.

This raises the question: how can compose be called initially with an undefined arg without triggering an error?

const compose = (...fns) =>
  (arg) =>
    fns.reduce( (composed, f) => f(composed), arg)

...
// Additional JavaScript functions and code
...

startTicking()

Answer №1

When you pass `undefined` as the initial argument to the `reduce` function, it does not automatically default to using the first element of the array. Instead, it simply uses `undefined` as the initial argument:

const arr = [1, 2, 3];
const traceSum = (a, b) => {
  console.log(a, b)
  return a + b
};
console.log("reduce without initial argument:",        arr.reduce(traceSum));
console.log("reduce with initial argument:",           arr.reduce(traceSum, 0));
console.log("reduce with initial argument undefined:", arr.reduce(traceSum, undefined));

Therefore, calling a function created by `compose` without supplying an argument is safe. In this case, `arg` will be explicitly `undefined`, causing each function to execute, but the initial value passing through them will be `undefined`:

const compose = (...fns) =>
  (arg) =>
    fns.reduce( (composed, f) => f(composed), arg)
    
const trace = message => value => {
  console.log(message, value);
  return value;
}

const test = compose(trace("one"), trace("two"));

console.log(test("hello"));
console.log(test());

It is important to ensure that your composed functions can operate without an initial value being passed:

const compose = (...fns) =>
  (arg) =>
    fns.reduce((composed, f) => f(composed), arg)

const excited = str => str + "!";
const loud = str => str.toUpperCase();
const greet = () => "hey";

const shout = compose(loud, excited);
const shoutGreeting = compose(greet, shout);

console.log(shout("stop"));                // works with initial value
console.log(shoutGreeting());              // works without initial value
console.log(shoutGreeting("hammer time")); // ignores initial value
console.log(shout());                      // error - initial value expected

Answer №2

When the reduce function is used without specifying an initialValue, it will start by applying the callback to the first two elements of the array.

For instance:

[2, 4, 6, 8, 10].reduce((x, y) => {
  console.log(x, ',', y, ',', x + y)
  return x + y;
}

This code snippet will produce the following output:

2 , 4 , 6
6 , 6 , 12
12 , 8 , 20
20 , 10 , 30

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

Tips for accessing the parent reference while binding using the .on() method

I needed to attach an event like this $("div").on("click", "li",function() { var div= $(this).parent().parent(); //this is what i'm using //..... }); above the <div> <ul> <li>1</li> <li>e2</l ...

Controlling date selection with Material UI's datepicker functionality

I have two date pickers, one for the start date and one for the end date. My goal is to have the end date picker disable all dates prior to the selected start date. For example, if you choose December 15th as the start date, then all dates before December ...

Updating contact list to a database table structure

Currently, my code displays the data in address books, but I would like it to be shown in a table instead. I attempted to use document.write to create the table, but I'm unsure how to populate the table with the data rather than the address book forma ...

How can I use Ajax to show only one div on the entire page while keeping the CSS and other header content intact

One of my clients is looking to integrate a merch shop into their website. The existing merch page is not visually appealing and doesn't match the aesthetic of the client's site. I am considering using AJAX GET to fetch the content of the merch p ...

The image map library functions seamlessly with React but encounters issues when integrated with Next.js

I have been working on a client project that requires the use of an image map. I searched for a suitable library, but struggled to find one that is easy to maintain. However, I came across this particular library that seemed promising. https://github.com/ ...

Utilizing JQuery to Modify XML File Content

Looking to retrieve data from an XML file using jQuery and display it in a textbox? If you want changes made in the textbox to reflect back in the original XML file, there are ways to achieve this. Here is some code that can help: <html><head&g ...

Managing date fields retrieved from a REST Api in AngularJS

One of the challenges I'm facing involves a REST API that sends back JSON data with dates formatted in ISO-8601 style: yyyy-MM-ddTHH:mm:ss: { id: 4 version: 3 code: "ADSFASDF" definition: "asdflkj" type: "CONTAINER" value: "12 ...

HTML5 Canvas Border

Hey Everyone, I've been working on an HTML5 canvas project where I set the canvas width to $(window).width(). Everything was going smoothly until I added a border, which caused a horizontal scroll to appear. Important: I attempted to use the innerWid ...

Encountering Errors with Angular JS Following Update from Version 1.1.0 to 1.1.1

After upgrading, I noticed that the ng-repeat function is taking significantly longer to load and is attempting to display additional content boxes without serving the actual content provided by $resource. I have pinpointed the issue to the update from ve ...

The addListener method in Google Maps iterates n times for a specific number of repetitions

When looking at the code below, the GetPropBasedOnRadius(); method loops for a certain number of times. I want to call that method only when the dragging event is completed. However, I am unsure how to do this. Any assistance on this matter would be great ...

Enhance fullness to facial features

Creating walls by forming faces using specific points is a successful process for me. However, I am now looking to add thickness to these walls, and I am unsure of the best approach. Below is the code I currently use to create the walls: makeWall(start, ...

Leveraging Iron Router for implementing query variable settings

Utilizing Iron Router, I aim to call a page and filter the results based on the route. In this scenario, the application facilitates the creation of items. Each item contains an array that can encompass zero to multiple tags: Item: { _id: <assigned b ...

AngularJS - Issue with Scope not being properly utilized in view when calling controller function

I'm attempting to update a variable within $scope in a controller function, and while the assignment is successful, it doesn't reflect in the view. app.controller('LoginCtrl', ['$scope', '$http', function ($scope, $ ...

Tracker.gg's API for Valorant

After receiving help with web scraping using tracker.gg's API and puppeteer, I encountered an error message when the season changed {"errors":[{"code":"CollectorResultStatus::InvalidParameters","message":" ...

Locally hosted website failing to transfer login details to external domain

Having trouble with an ajax call that is supposed to retrieve data from a web page, but instead returns a jQuery parse Error. Even though I can access the page directly, the ajax call doesn't seem to be working and storing the result properly. Below ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

Troubleshooting issues with JavaScript events in order to effectively implement popovers

I am facing an issue on a webpage that contains a significant amount of JavaScript. The Twitter bootstrap's popover widget is not functioning as expected. Specifically, when I hover over the icon that should trigger the "popover," nothing happens. I h ...

Utilize AngularJS's OrderBy feature to iterate through the list for navigation in ascending order by Index

I am looking to customize the order of an Object-array using ng-repeat based on their index keys in ascending order. $scope.paneContainer = {books:[{}] } ; $scope.paneContainer.books[0].science = { title:"science", content:"web/app/views/partials/scienc ...

React app frequently retrieves images from the server whenever react-router is being utilized

I am currently working on a create-react-app project that utilizes the react-router-dom. Within this project, I have several Components that function as pages in a Single Page Application. Each page includes the following component: return ( <im ...

iterating over a list of files using JavaScript

I am currently working on setting up individual ajax requests for each file being uploaded. I have a functioning ajax call that creates a record, returns some html, and provides the tempID of the record which is then used in another ajax call that triggers ...