0

Write a function that accepts a callback method and returns a function that will execute only if all the parameters passed to it are defined, otherwise it returns nothing. Here's what I wrote why is not it working?

function sumof(checkof) {
  sum = 0
  for (a in this.myNumbers)
    if (checkof(a) == 1)
      sum += a
  else
    return null
  return sum

}

function check(a) {
  if (a == null)
    return 0
  else
    return 1

}

function init() {
  let myNumbers = [22, 1, 8, 4, 17];
  var x = myNumbers.sumof(check)
  alert(x)
}
init()

8
  • 7
    You're failing to tell us what exactly is wrong – "why isn't it working" is never really enough. Commented Apr 16, 2021 at 12:25
  • 3
    (But why would you imagine myNumbers.sumof(...) would work?) Commented Apr 16, 2021 at 12:26
  • 1
    change it to sumof(myNumbers)\ Commented Apr 16, 2021 at 12:26
  • Your function is not a method of your array. You'll need to separate them in the function call. Commented Apr 16, 2021 at 12:26
  • @Itamar no, because the first argument to sumof is supposed to be a callback function. Commented Apr 16, 2021 at 12:30

2 Answers 2

2

myNumbers.sumof doesn't work because sumof is a standalone function, not part of Array.

this.myNumbers also makes no sense because myNumbers isn't global.

The simplest solution is to pass myNumbers into your sumof function:

function sumof(checkof, myNumbers) {
  sum = 0
  for (a in myNumbers)
    if (checkof(a) == 1)
      sum += a
  else
    return null
  return sum

}

function check(a) {
  if (a == null)
    return 0
  else
    return 1

}

function init() {
  let myNumbers = [22, 1, 8, 4, 17];
  var x = sumof(check, myNumbers)
  alert(x)
}
init()

Sign up to request clarification or add additional context in comments.

Comments

0

you are calling it like a array property method. but you have defined that function as a standalone function. you should add your function as a array property method.

Array.prototype.sumof = function(checkof) {
    if ( ! this.length ) {
        return null;
    }
    sum = 0;
    for (i = 0; i < this.length; i++) {
        a = this[i];
        if (checkof(a) == 1) {
            sum += a;
        }
    }
    return sum;
};


function check(a) {
    if (a == null)
        return 0;
    else
        return 1;

}

function init() {
    let myNumbers = [22, 1, 8, 4, 17];
    var x = myNumbers.sumof(check);
    console.log(x);
    myNumbers = [22, 1, null, 4, 17];
    x = myNumbers.sumof(check);
    console.log(x);
}
init();

also if you are using Array property method, you should avoid using for..in. because when you looping through this, it will also have your new method too. use for with array length.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.