Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- export class NestedFrequencyTable
- constructor( initialData ) {
- this._categories = {};
- if( initialData )
- dojo.mixin( this._categories, initialData );
- }
- // get the sum of all the category counts
- total() {
- // calculate total if necessary
- var t = 0;
- for( var k in this._categories ) {
- var v = this._categories[k];
- t += v.total ? v.total() : v;
- }
- return t;
- }
- // decrement the count for the given category
- decrement( slotName, amount ) {
- if( ! amount )
- amount = 1;
- if( !slotName )
- slotName = 'default';
- else
- slotName = slotName.toString();
- if( this._categories[slotName] )
- return this._categories[slotName] = Math.max( 0 , this._categories[slotName] - amount );
- else
- return 0;
- },
- // increment the count for the given category
- increment( slotName, amount ) {
- if( ! amount )
- amount = 1;
- if( !slotName )
- slotName = 'default';
- else
- slotName = slotName.toString();
- return ( this._categories[slotName] = (this._categories[slotName] || 0) + amount );
- },
- // get the value of the given category. may be a number or a
- // frequency table.
- get( slotName ) {
- return this._categories[slotName] || 0;
- },
- // get a given category as a frequency table
- getNested( path ) {
- if( typeof path == 'string' )
- path = path.split('/');
- if( ! path.length )
- return this;
- var slotName = path[0].toString();
- var slot = this._categories[slotName];
- if( ! slot || ! slot._categories )
- slot = this._categories[slotName] = new NestedFrequencyTable( slot ? { "default": slot+0 } : {} );
- if( path.length > 1 ) {
- return slot.getNested( path.slice(1) );
- } else
- return slot;
- },
- // returns array of category names that are present
- categories() {
- return Object.keys( this._categories );
- },
- toString() {
- return this.total().toPrecision(6).toString().replace(/\.?0+$/,'');
- },
- valueOf() {
- return this.total();
- },
- // iterate through the categories and counts, call like:
- //
- // tbl.forEach( function( count, categoryName ) {
- // // do something
- // }, this );
- //
- forEach( func, ctx ) {
- var c = this._categories;
- if( ctx ) {
- for( var slotName in c ) {
- func.call( ctx, c[slotName], slotName );
- }
- } else {
- for( var slotName in c ) {
- func( c[slotName], slotName );
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement