Skip to content

Instantly share code, notes, and snippets.

@bwindels
Created November 28, 2014 14:51
Show Gist options
  • Save bwindels/be9c6f89135cd574ae56 to your computer and use it in GitHub Desktop.
Save bwindels/be9c6f89135cd574ae56 to your computer and use it in GitHub Desktop.
Generics for higher order functions
function map<I,O>(array:I[], mapper:(value:I) => O) : O[] {
var result:O[] = [];
var index = 0;
for(;index < array.length; ++index) {
result.push(mapper(array[index]));
}
return result;
}
function reduce<I,O>(array:I[], reducer:(reduced:O, value:I) => O, initialValue: O) : O {
var result = initialValue;
var index = 0;
for(;index < array.length; ++index) {
result = reducer(result, array[index]);
}
return result;
}
interface Fooable {
foo:number
}
interface Barable {
bar:number
}
class FooImpl implements Fooable {
constructor(public foo:number) {}
}
var values = [1,2,4,5,6];
var mapped = map(values, (x:number) : Fooable => new FooImpl(x));
var squared = map(mapped, x => x.foo * x.foo);
var reduced = reduce(squared, (r, x) => x+","+r, "");
alert(reduced);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment