Chapter 5 of Eloquent JavaScript's 3rd Edition presents Exercise 3

I'm struggling with an exercise in the latest edition of a book, specifically in Chapter 5 which covers Higher-Order Functions. The prompt for the exercise is as follows:

"Similar to the some method, arrays also contain an every method. This method returns true when a given function returns true for every element in the array. You can think of some as the equivalent of the || operator for arrays, and every as the equivalent of the && operator."

The task is to create an every function that takes an array and a predicate function as arguments. Two versions are required: one using a loop and the other utilizing the some method."

In the provided code sandbox, the function template looks like this:

function every(array, test) {
// Your code here.
}

Sample test cases are shown below:

console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true

As I review the test cases, I'm struggling to understand how to pass the array parameter to the test parameter, especially considering the test parameter can be any function. The instructions simply mention "a predicate function." While I could continue using n as the variable, it seems like the author wants me to create my own array.prototype.every() method.

Can anyone provide insight into what this exercise is aiming for? Or perhaps point out something I may be overlooking?

Answer №1

When you invoke a function, you do not need to know the specific names of the parameter variables. All you have to do is pass the desired value as an argument, and the function will take care of the rest.

Therefore, you can simply execute the test() function with the element currently being processed in the array as the argument.

function every(array, test) {
  for (let i = 0; i < array.length; i++) {
    if (!test(array[i])) {
      return false;
    }
  }
  return true;
}

console.log(every([1, 3, 5], n => n < 10));
// → true
console.log(every([2, 4, 16], n => n < 10));
// → false
console.log(every([], n => n < 10));
// → true

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

ReactJS & MobX: Unusual TypeError Occurs - Functionality Issue?

This code snippet defines the SidenavStore.js, which determines if the Sidenav should be visible or not by default: const SidenavStore = types .model('SidenavStore', { isSidenavVisible: types.optional(types.boolean, true), }) .actions( ...

What causes JavaScript to be unable to run functions inside other functions?

Functional languages allow functions to be executed within the argument brackets of nested functions. In JavaScript, which drew inspiration from Scheme, what is the equivalent? f( f ( f ( f))) console.log( 1 + 1 ) //2 How does JavaScript execut ...

The head.js feature similar to "Modernizr" does not recognize ms-edge

It has come to my attention that the head.js script is unable to detect the Microsoft "Edge" browser correctly. In addition, it erroneously adds classes like chrome and chrome55 to the <html> element. Is there a better way to handle this issue? The ...

Tips for managing cookies in an Angular.js project

At the moment, I am utilizing an AngularJS application. To store certain values in a cookie, I incorporated the angular-cookies-min script to add values to cookies. The following code snippet was used to save values to a cookie: $cookieStore.put("userIn ...

What steps can I take to determine the status of my Axios post request?

Here's a simple task I'd like to accomplish using Axios for an Ajax request. When a user clicks on a button, I want to fire an Ajax request. While the request is processing or until it's completed, I would like to disable the button or impl ...

Ways to restart script following Ajax call when additional search results are loaded

Implementing Klevu's search results page has been a manageable task so far. However, I encountered an issue where the search results page is displaying an Add to Cart button that should not be there, as confirmed by Klevu themselves. Their suggestion ...

Is there a way to trigger a function upon the loading of a template in Angular 2?

I'm a newcomer to angular2 and I need to trigger a function when a template loads or initializes. I have experience with achieving this in angular1.x, but I'm struggling to figure out how to do it in angular-2. Here's how I approached it in ...

How can you generate a Base64 string with Node.js?

I recently utilized the html2pdf npm package to generate a base64 string of a PDF file and then sent it to my Node.js server. I used Nodemailer to send this PDF as an email attachment by configuring the mailOptions object like so: let mailOptions ...

the key of the global variable object is not displaying as being defined

Currently tackling some old legacy code that heavily relies on JQuery, and I'm stuck at a critical juncture. It seems like the process begins with initializing vm.products in newView = new DOMObj(). Then comes the data call, where a worker iterates t ...

Using Angular JS for Traditional Multi-page Websites

Lately, I've been diving into Angular 2 and I have to admit, it's an impressive framework for building single-page applications. But here's the thing - how would one go about integrating Angular with a traditional website (maybe using codei ...

Retrieve all HTML dependencies, such as JavaScript and CSS files, using the same method as a web browser

I am currently working on a Single Page Application (SPA). My main objective is to evaluate the performance of the application using . Given that the application is an SPA, I want to simulate a scenario where all static content is loaded when a user firs ...

Why does Vue only change a specific array element without updating the DOM?

My curiosity is piqued by a puzzling issue with updating specific items in an array using Vue.js. The documentation cautions that: Due to limitations in JavaScript, Vue cannot detect the following changes to an array: When you directly set an item with th ...

What benefits does minifying server-side nodejs code provide?

Is there a benefit to minifying Node.js code in the same way as minifying JavaScript, particularly for reducing size and improving network download speed? When a file is required in Node.js, it is loaded into V8 and processed and stored in memory in some f ...

To begin, formulating a blank state entity containing a collection of key-value pairs with JSON objects as the values. Subsequently, modifying the contents of

I am working on setting up a reactJS state with an empty array to start. When I receive a message in the form of a JSON object, I want to add a key-value pair to the array, using the received message as the value and a specified key. For example: We have ...

Adding a class to a PHP file using AJAX response

I have been developing a website that features a like button attached to user-generated posts. My goal is to update the like count of a post whenever a user likes it, but I am encountering an issue where the entire post gets affected. Below is the code fo ...

Implementing Button Activation and Deactivation Upon Checkbox Selection in JQuery

When a single checkbox is selected, the Edit and Delete buttons are enabled while the Add button is disabled. If two or more checkboxes are selected, the Delete button is enabled while the Add and Edit buttons are disabled. This is my HTML code: < ...

Issues with sending parameters in JQuery Ajax POST request

Currently, I am delving into Ajax and encountering some issues with sending requests from the client side. I have a jsp file located at "/web" on my local server to manage requests. Though unsure if this is the best approach or if it should be handled by ...

Information on the Manufacturer of Devices Using React Native

Struggling to locate the device manufacturer information. Using the react-native-device-info library produces the following output. There seems to be an issue with handling promises. I need to store the device manufacturer value in a variable. const g ...

Why is the button missing from the codepen?

I attempted to recreate the code from this Codepen link: https://codepen.io/jakaric/pen/mjJQvg However, unlike what you see here (in the run result), the liquid "Pretty little button" is not showing up in my local files. On Codepen, there is no library me ...

Having trouble getting the form to submit with jQuery's submitHandler

I am in the process of converting a contact form to AJAX so that I can utilize the success function. Currently, I am encountering an issue where the code is halting at the submitHandler section due to it being undefined. Can anyone identify why my submitHa ...