Invert the output of the callback function by using the not(callback) method

Within my filtering function, I am passing a testing function:

var array = [1,3,5,7,9]
function bigger(n){return n > 5}

function filterArray(data,testfn){
  return data.filter(e=> testfn(e))}

console.log(filterArray(array,bigger))
>>>[7,9]

Now, I want to be able to write

console.log(filterArray(array,not(bigger)))
>>>[1,3,5]

Answer №1

One way to enhance your code is by creating a function called not. This function takes in another function as an argument and then returns a new function that provides the opposite result of calling the original function:

var array = [1, 3, 5, 7, 9];

function bigger(n) {
  return n > 5
}

function filterArray(data, testfn) {
  return data.filter(e => testfn(e))
}

function not(f) {
  return function(n) {
    return !f(n);
  }
}


console.log(filterArray(array, bigger));
console.log(filterArray(array, not(bigger)));

Answer №2

If you're looking to achieve a similar outcome, you could try implementing the following approach:

var array = [1, 3, 5, 7, 9]

const isBiggerThan = (n) => n > 5
const isNot = (fn) => (n) => !fn(n)
const filterArray = (data, testfn) => data.filter(e => testfn(e))    

console.log(filterArray(array, isBiggerThan))
console.log(filterArray(array, isNot(isBiggerThan)))

The concept behind this function setup involves using the isNot function to produce a new function that simply flips the result of the passed-in function.

Answer №3

In my approach, I typically use a similar strategy.

let numbers = [2,4,6,8,10];
const isSmaller = (num) => num <= 8;

console.log(numbers.filter(item => isSmaller(item)));

Answer №4

To handle variadic functions: Gathering arguments in an array named "arguments" and passing them to the function.

function not(myFunction){
  if (typeof myFunction != "function"){return !myFunction } 
   return function (...args) {
      return !myFunction.apply(null,args)
   }
 }

In summary:

const not = f => (...a) => !f.apply(null,a)

Additionally, to ensure it works for all values - checking if a function is being passed. This allows using it like this not(bigger(1,2)):

 function not(anything){
  if (typeof anything != "function"){return !anything } 
   return function (...args) {
      return !anything.apply(null,args)
   }
 }


var variable = true
console.log(not(bigger(6))) >>> true
console.log(not(variable))) >>> false
console.log(not(false))) >>> true

In summary:

const not = f => typeof f != "function" ? !f : (...a) => !f.apply(null,a)

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

How do you set a default value for a dropdown menu (<select>) and then update it later on?

In my grid, each row has a dropdown menu and I want to display its state from the database. The dropdowns are defined with a selected option specified for preselecting the value from the DB. <select id='selectId'> <option value='1& ...

Updating the Highcharts chart when new data is available

Utilizing Highcharts, I am looking to have this chart update every second. Here's my current setup: JSFiddle I've implemented a timer with window.setInterval(updateChart, 1000); which successfully updates data each second. However, I'm uns ...

In Firefox, an error occurs when Window.getComputedStyle does not adhere to the Element interface

After successfully appending data to the HTML element using the code below: $("#bookListDiv").append(data.HTMLString); I wanted to enhance the display by adding a fadein animation. So, I made some adjustments to achieve this effect: $(data.HTMLString).h ...

Having trouble locating the correct position in the array

In my database, there is a table with columns like time and text, and I need to extract all entries from any column into separate string arrays. I have successfully created two string arrays named texts and times to store the entries. Now, I am trying to ...

Invoke a JavaScript function within a PHP file

My JavaScript file, named "my_js_stuff.js", has the following code: function my_js_function() { jQuery.ajax({ url: my_ajax_script.ajaxurl, data: ({action : 'get_my_comments'}), success: function() { //Do stuff here } }); This file is ...

pressure exerted on the body

Recently, I've been working on a project for the website . One of the main issues I've encountered is that the <body> element is consistently 20px lower than it should be at the top. This has led to visible problems with the background grad ...

What is the url of the file at input.files[i]?

I've encountered an issue with my JavaScript code. Currently, when a user uploads a file, the code grabs the file name. However, I need it to fetch the file's URL on the user's PC instead. How can I implement this? This is my code snippet: ...

Rectify the functionality of collapsing and expanding sections

I am utilizing the bootstrap 4 alpha 6 version in my project. On my page, I have multiple blocks that I would like to expand/collapse by clicking on a main button (with the id of 'expand-collapse'). Additionally, each block has its own individual ...

Using the setTimeout function in Vue.js to trigger the play of an audio file at a specified

I have set up a Vue-audio player in my Vue.js application using the AudioPlayer component. This is my code: <template> <vue-audio id = "myAudio" :file= "file1"/> </template> <script> import VueAudio from 'vue-audio'; ...

Can a plugin be executed as a test?

I am currently using HTMLhint, however, I would like to have it run as a test rather than just through the command line plugin. Is there a way to achieve this and if so, how can I do it? I have searched online but haven't been able to find a solution ...

Trouble with callback execution during async foreach loop when using collection.save() in Node.js

In my quest to store records in a mongoDB collection while in an async foreach loop, I encountered an issue where the code seems to be skipping the save part altogether. Here is the relevant snippet: async.forEach(data, function(item, callback) { va ...

Determining the Nearest Form to an Element using jQuery

I developed a JavaScript/jQuery script that allows me to check all checkboxes within a form. The function works effectively, but the issue is that it checks all checkboxes on the page regardless of their form wrapper. Here is the function: function toggl ...

Leveraging the power of HTML 5 to dynamically insert content into a jQuery table

I am experiencing an issue with my jquery stock ticker. It displays the latest stocks including Company Name, stock price, and percentage changed. The stock price can be in GBP, USD, or YEN, but the current ticker does not indicate the currency. I attemp ...

Is it possible to declare an array with a non-constant length?

I'm a bit confused about how to declare arrays in C. I understand that you can declare arrays like this: int a[20]; // Allocates space for an array of 20 integers int b[] = {32, 431, 10, 42}; // Length is automatically calculated based on the number ...

JNI accessing multiple arrays in an array object

My current project involves writing a performance benchmark for various sorting algorithms in Java. To enhance my understanding and explore new possibilities, I decided to delve into the realm of JNI (Java Native Interface). I aim to sort a collection of i ...

Firebase Function mistakenly logs incorrect key to database entry

I have a cloud function that I am calling directly in my app. Here is the code snippet: const functions = require('firebase-functions'); const admin = require('firebase-admin'); admin.initializeApp(); exports.sharePost = functions.ht ...

Is there a way to modify AJAX response HTML and seamlessly proceed with replacement using jQuery?

I am working on an AJAX function that retrieves new HTML content and updates the form data in response.html. However, there is a specific attribute that needs to be modified before the replacement can occur. Despite my best efforts, I have been struggling ...

There was a mistake: _v.context.$implicit.toggle cannot be used as a function

Exploring a basic recursive Treeview feature in angular4 with the code provided below. However, encountering an error when trying to expand the child view using toggle(). Encountering this exception error: ERROR TypeError: _v.context.$implicit.toggle i ...

Guide on invoking a page dynamically upon clicking a dropdown link within an HTML table

There is an HTML table with dropdown links to various columns. A click on the link will redirect to it successfully. The goal is to call a different HTML table on the same page when a specific drop down column is selected. Sample code: <div id="tbl" ...

Troubleshooting Issue: jQuery Hide/Show Functionality Not Behaving as Expected Inside If

Trying to create a jQuery slideshow but encountering some difficulties. The issue lies with a variable that should hide or show images based on the navigation buttons pressed. However, only img1 is showing and none of the other images are displaying. Des ...