Skip to main content

Using "this" as an Argument of Callback method[javaScript]

function destroyer(arr) {
  // Remove all the values
  var arg = Array.from(arguments);
  var initial=arg[0];
  var destr=[];
  for(i=1;i<arg.length;i++)
    destr[i-1]=arg[i];
  for(i=0;i<destr.length;i++)
  initial=initial.filter(tester,destr[i]);
  return initial;
}
function tester(value){
  if(value==this)
    return false;
  else
  return true;
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);
//OUTPUT : [1,1]

Explanation :

  • .filter() will remove the present element if callback function returns false.
  • 'arguments' is a language defined object which has the arguments passed into the function,but this will not be in array format.
  • Array.from(arguments) returns the arguments in array format.
  • Second argument passed to the .filter() method is visible to callback function (in this case "tester") via "this" object inside the callback function.

Comments

Popular posts from this blog

ASCII to Decimal conversion

#include "msp430.h"                     ; #define controlled include file         NAME    main                    ; module name         PUBLIC  main                    ; make the main label vissible                                         ; outside this module         ORG     0FFFEh         DC16    init                    ; set reset vector to 'init' label         RSEG    CSTACK                  ; pre-declaration of segment         RSEG    CODE      ...

Event Sourcing with CQRS.

  The way event sourcing works with CQRS is to have  part of the application that models updates as writes to an event log or Kafka topic . This is paired with an event handler that subscribes to the Kafka topic, transforms the event (as required) and writes the materialized view to a read store.