Skip to content
Snippets Groups Projects
Select Git revision
  • dd81d1ad2bab8444d9de8aa72fdefc0aa468f15a
  • master default protected
  • rednatco-v2
  • base-pairs-ladder
  • rednatco
  • test
  • ntc-tube-uniform-color
  • ntc-tube-missing-atoms
  • restore-vertex-array-per-program
  • watlas2
  • dnatco_new
  • cleanup-old-nodejs
  • webmmb
  • fix_auth_seq_id
  • update_deps
  • ext_dev
  • ntc_balls
  • nci-2
  • plugin
  • bugfix-0.4.5
  • nci
  • v0.5.0-dev.1
  • v0.4.5
  • v0.4.4
  • v0.4.3
  • v0.4.2
  • v0.4.1
  • v0.4.0
  • v0.3.12
  • v0.3.11
  • v0.3.10
  • v0.3.9
  • v0.3.8
  • v0.3.7
  • v0.3.6
  • v0.3.5
  • v0.3.4
  • v0.3.3
  • v0.3.2
  • v0.3.1
  • v0.3.0
41 results

grouping.ts

Blame
  • user avatar
    David Sehnal authored
    90077b57
    History
    grouping.ts 1.43 KiB
    /**
     * Copyright (c) 2017 mol* contributors, licensed under MIT, See LICENSE file for more info.
     *
     * @author David Sehnal <david.sehnal@gmail.com>
     */
    
    import { Column } from '../db'
    
    export interface Grouping<V, K> {
        map: Map<K, V[]>,
        keys: ReadonlyArray<K>,
        groups: ReadonlyArray<ReadonlyArray<V>>
    }
    
    class GroupingImpl<K, V> {
        readonly map = new Map<K, V[]>();
        readonly keys: K[] = [];
        readonly groups: V[][] = [];
    
        add(a: V) {
            const key = this.getKey(a) as any;
            if (!!this.map.has(key)) {
                const group = this.map.get(key)!;
                group[group.length] = a;
            } else {
                const group = [a];
                this.map.set(key, group);
                this.keys[this.keys.length] = key;
                this.groups[this.groups.length] = group;
            }
        }
    
        getGrouping(): Grouping<V, K> {
            return { keys: this.keys, groups: this.groups, map: this.map };
        }
    
        constructor(private getKey: (v: V) => K) { }
    }
    
    export function Grouper<V, K>(getKey: (x: V) => K) {
        return new GroupingImpl<K, V>(getKey);
    }
    
    export function groupBy<V, K>(values: ArrayLike<V> | Column<V>, getKey: (x: V) => K) {
        const gs = Grouper(getKey);
        if (Column.is(values)) {
            const v = values.value;
            for (let i = 0, _i = values.rowCount; i < _i; i++) gs.add(v(i));
        } else {
            for (let i = 0, _i = values.length; i < _i; i++) gs.add(values[i]);
        }
        return gs.getGrouping();
    }