Skip to content

Commit

Permalink
O(N^2) -> O(N) loop for a big speedup
Browse files Browse the repository at this point in the history
  • Loading branch information
danvk committed Mar 18, 2015
1 parent 9f7d45e commit 616c3c1
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 12 deletions.
3 changes: 3 additions & 0 deletions lib/underscore.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,8 @@ declare module "underscore" {

declare function chain<S>(obj: S): any;
declare function any<T>(list: Array<T>, pred: (el: T)=>boolean): boolean;

declare function each<T>(o: {[key:string]: T}, iteratee: (val: T, key: string)=>void): void;
declare function each<T>(a: T[], iteratee: (val: T, key: string)=>void): void;
}

14 changes: 10 additions & 4 deletions src/BigBedDataSource.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,20 +76,26 @@ function parseBedFeature(f): Gene {

function createBigBedDataSource(remoteSource: BigBed): BigBedSource {
// Collection of genes that have already been loaded.
var genes: Array<Gene> = [];
var genes: {[key:string]: Gene} = {};

// Ranges for which we have complete information -- no need to hit network.
var coveredRanges: Array<ContigInterval<string>> = []

function addGene(newGene) {
if (!_.findWhere(genes, {id: newGene.id})) {
genes.push(newGene);
if (!genes[newGene.id]) {
genes[newGene.id] = newGene;
}
}

function getGenesInRange(range: ContigInterval<string>): Gene[] {
if (!range) return [];
return genes.filter(gene => range.intersects(gene.position));
var results = [];
_.each(genes, gene => {
if (range.intersects(gene.position)) {
results.push(gene);
}
});
return results;
}

function fetch(range: GenomeRange) {
Expand Down
13 changes: 5 additions & 8 deletions test/BigBedDataSource-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,8 @@ describe('BigBedDataSource', function() {
return createBigBedDataSource(new BigBed('/test/data/ensembl.chr17.bb'));
}

// Shorthand
function ci(contig, start, stop) {
return new ContigInterval(contig, start, stop);
}

it('should extract features in a range', function(done) {
this.timeout(5000);
console.time('extract');
var source = getTestSource();

// No genes fetched initially
Expand All @@ -34,7 +28,6 @@ describe('BigBedDataSource', function() {

// Fetching that one gene should cache its entire block.
source.on('newdata', () => {
console.timeEnd('extract');
var tp53s = source.getGenesInRange(tp53range);
expect(tp53s).to.have.length(1);

Expand All @@ -43,6 +36,10 @@ describe('BigBedDataSource', function() {
expect(tp53.exons).to.have.length(11);
done();
});
source.rangeChanged(tp53range);
source.rangeChanged({
contig: tp53range.contig,
start: tp53range.start(),
stop: tp53range.stop()
});
});
});

0 comments on commit 616c3c1

Please sign in to comment.