Skip to content

Instantly share code, notes, and snippets.

@bcherny
Created September 13, 2016 16:41
Show Gist options
  • Save bcherny/2db0ee67c616d2179d242d1b4546ab72 to your computer and use it in GitHub Desktop.
Save bcherny/2db0ee67c616d2179d242d1b4546ab72 to your computer and use it in GitHub Desktop.
Compile time complexity and running time checks

Complexity

As a decorator:

interface Record {}

@Complexity("n")
function getRecord(userId: number): Record {
  return db.getRecords().findWhere({userId}) // Error! Expected O(n) complexity, found O(log(n)) complexity
}

Or, as a type:

interface Record {}

function getRecord(userId: number) in n2: Record {
  return db.getRecords().findWhere({userId}) // Error! Expected O(n) complexity, found O(log(n)) complexity
}

Runtime

@Budget(2ms)
function invert<T>(object: {[key: string]: T}): {[key: string]: string} {
  const result = {}
  for (let key of object) {
    result[object[key]] = key
  }
  return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment