Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Official ZPE/YASS documentationcounter

Official ZPE/YASS documentationcounter

counter (list items[, function f]) ⇒ map

Generates a map which contains the count of all instances of each value from the items array. If a function is supplied to this, each item will be passed to the function first.

First available: Version 1.4.1.0

Using counter

Using a function is useful when you are working with an array of arrays, since the function compares based on the value as a whole. Given some lambda function, only a part of the inner arrays could be returned and processed. The counter function supports the optional f parameter.

The following example is a standard use of counter.

YASS
function main($args)

  //This variable used to be called $list, but since ZPE 1.5, list is a reserved keyword and cannot be used
  $l = [["Ashley", 32], ["Jonathan", 64], ["Adam", 12], ["Jamie", 32], ["Frank", 64]]

  //By passing this to the function, we can return the second index (index 1) from the inner list and count that
  $counted = counter($l, function($x) return list_get_at_index ($x, 1) end function)

  //Should return [12 => 1, 64 => 2, 32 => 2]
  print($counted)

end function
        

It can also be used nicely with object instances to count properties of them:

YASS
struct person

  $fname = ""
  $sname = ""
  $grade = ""

  function _construct($f, $s, $g)

    this->$fname = $f
    this->$sname = $s
    this->$grade = $g

  end function

  public function getGrade()
   return this->$grade
  end function

end struct


function main()

  $p1 = new person("Ashley", "Peters", "C")
  $p2 = new person("James", "Peters", "A")
  $p3 = new person("Frank", "Adams", "B")
  $p4 = new person("Ashley", "Adams", "A")
  $p5 = new person("Jamie", "Bond", "A")
  $p6 = new person("Alec", "Bond", "C")

  $people = [$p1, $p2, $p3, $p4, $p5, $p6]

  //Should result in [A => 3, B => 1, C => 2]
  $result = counter($people, function($x) return $x->getGrade() end function)
  print($result)
  //Should print 3
  print($result["A"])
end function
Comments
Feedback 👍
Comments are sent via email to me.