Frequency
Rather than keeping track of values, maybe you want to keep track of the number of times an event occurs, without caring much about the data itself.
In ixfx, we can use Trackers.frequency . Note that the object is mutable.
Adding and clearing
import { Trackers } from "https://unpkg.com/ixfx/dist/bundle.js"
// Create an instanceconst freq = Trackers.frequency();
// Add data, here several at oncefreq.add(`apples`, `oranges`, `apples`, `pears`, `pears`);
// Get frequencies as an arrayconst t = freq.toArray(); // [ ["apples", 2], ["oranges",1],["pears",2] ]
Clear all data
freq.clear();
Calculating
Get the count of a specific group. Returns undefined
if group is not found.
const f = freq.frequencyOf(`apples`); // 2
It can be useful to work with the relative frequency rather than the absolute amount. For example, apples
appears 40% of the time:
const rel = freq.relativeFrequencyOf(`apples`); // 0.4
To find the smallest, largest, average frequencies as well as the total frequency (ie. how many things have been added):
// Returns {min, max, avg, total}const mma = freq.minMaxAvg();console.log(`Average frequency is ${mma.avg}`);
Iterating
You can get the data as an array and iterate:
const data = freq.entries(); // freq.toArray() gives same resultfor (const [group, count] of data) { console.log(`${group} has a count of ${count}`); // apples has a count of 2...}
Custom objects
To keep track of objects, provide a function that creates a string for the items you’re adding. This allows you to group by different fields, or some combination of fields.
In the below example, cars are grouped by their make:
import { frequency } from "https://unpkg.com/ixfx/dist/trackers.js"
// Two carsconst cars = [ { make: `Toyota`, model: `Corolla`, year: 1980 }, { make: `Honda`, model: `Civic`, year: 1985 }]
// Count cars by makeconst freq = frequency(car => car.make);
// Add array of carsfreq.add(...cars);
// Count a groupfreq.frequencyOf(`Toyota`); // 1
// Or by object, which uses the same stringify functionfreq.frequencyOf(cars[1]); // 1
Demo
The below demo calculates frequency distribution of letters in a string.