2023-05-18

 18 May 2023

Write a Function that Returns the Number of Elements where it's Callback is True

Taken from Execute Program

Write a function that takes an array and a callback function, then returns the number of elements where callback returns true. Use .forEach to iterate through the array.

Solution

This is the answer I came up with:

// Function type (takes in param of any type, returns any type)
type Callback = (param: any) => any

function count(arr: Array<any>, callback: Callback) {
  let count = 0
  arr.forEach(element => {
    if (callback(element)) {
      count += 1
    }
  })
  return count
}

Testing

Solution tested in REPL:

https://www.typescriptlang.org/play?#code/PTAEDEFcDsGMBcCWB7ap4E8AOBTUAKeAQwGscBnURNLIgJyIFtRkAzUI6DdbHAGlB0c8SHWiVO3TLgCUAWABQ0vAGEiAG3UAjIrBKgAvAVoNGALg5cZhgHyWMixaxgIUaWMhjx89OhYCCdAwYADySNgKwGtq6JBZqmjp61gDeiqCg6sKgHl6GoAAM6RxBAHSsyHQAoroAFvg4WYw40PC2oGkKGRmI7PhRibENTS3wMqnF3TmeraAA1EYAjJOgAL7Fq-JdgsKi7jPwiusKih7iyFml6sgA5vinB-gA2osCAEwCAMwCACwAugI8AY7ECDEZPjI+A8vM9XqAPqBvqB-oD2ng7ItIdDWs8EXCfgIAKzvAQADgBoCBIMMYPhWIUuRxTwA5ERmQJmVpmRSqZSaUZmQATZn0xneJ48tH80BCkVQhTWECgOFIhEFARFBRAA

Copyright © Paramdeo Singh · All Rights Reserved · Built with Jekyll

This node last updated November 7, 2023 and is permanently morphing...

Paramdeo Singh Guyana

Generalist. Edgerunner. Riding the wave of consciousness in this treacherous mortal sea.

Technology Design Strategy Literature Personal Blogs
Search Site

Results are from Blog, Link Dumps, and #99Problems