Sunday, September 11, 2016

Reporting Value Runs in Sequential Data

Summary

liniarGroup accepts an array, and a mapping function. It will output an array of objects describing the index ranges of contiguous sequences, based on the mapping function.

Usage

A Simple Example

window.BN.liniarGroup([0, 0, 1, 2, 2], (v) => v);

results in:

0 - 1,  0
2, 1
3,  2

mapped value: 0, range: "0 - 1", 
mapped value: 1, range: "2"
mapped value: 2, range: "3 - 4"

note: console.table() is useful for displaying this data

A More Complex Example

------------------------

window.BN.liniarGroup(phonebook.entries, (v) => { 
 if (!v.getName()) return "undefined";
 return v.getName()["Last Name"]; 
});

results in:

range: "0 - 50",  mapped value: "Anderson"
range: "51-55", mapped value: "Appleton"
range: "56-57", mapped value: "Avery"
range: "60", mapped value: "Axelrod"

Code

window.BN = window.BN || {};
window.BN.liniarGroup = (arraryIn, fnMap) => {
    let results = [];
    let prevIdx = 0;
    let prevVal = fnMap(arraryIn[0]);
    let lastFoundIndex = undefined;
    for(var i=1; i<arraryIn.length; i++) {
        let iter = arraryIn[i];
        let mappedVal = fnMap(iter);
        if (mappedVal === prevVal) {
            
        }
        else {
            let range = prevIdx === (i-1) ? prevIdx.toString() : prevIdx + " - " + (i-1);
            results.push({"range" : range, "mapped value": prevVal});
            prevVal = mappedVal;
            prevIdx = i;
        }
    }
    let range = prevIdx === (i-1) ? prevIdx.toString() : prevIdx + " - " + (i-1);
    results.push({"range" : range, "mapped value": prevVal});
    return results;
}


Friday, September 2, 2016

Inner Classes in TypesScript

Example of Inner Classes in Typescript

(available since 1.6)

The implementation method is actually "class expressions".

We use them to create a private "inner class" (e.g. myClassExpresion) which is instantiated with the parent class's this and assigned to a public property of the parent class (e.g. innerClassInstance).

Unfortunately, the "inner class" does not have access to private or protected members of the parent.

class Greeter {
    constructor(message: string) {
        this.greeting = message;
    }

    //inner class definition
    private myClassExpresion = class {
        constructor(private parent: Greeter){}
        public say(x: number) {
            return this.parent.greet() + " " + x;
        }
    }

    public greet() {
        return "Hello, " + this.greeting;
    }

    // inner class instance
    public innerClassInstance = new this.myClassExpresion(this);

    private greeting: string;
}

// USAGE
let greeter = new Greeter("I am number");
alert(greeter.innerClassInstance.say(9));

note: the inner class must be defined within the parent class before it is instantiated.