O'Reilly logo

TypeScript Blueprints by Ivo Gabe de Wolff

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Adding utility functions

We will write several utility functions in lib/game/utils.ts. With flatten, we will transform an array of arrays into one array.

export function flatten<U>(source: U[][]): U[] { 
  return (<U[]>[]).concat(...source); 
} 

With update, we can modify some properties of an object. This is the same function as in previous chapters.

export function update<U extends V, V>(old: U, changes: V): U { 
  const result = Object.create(Object.getPrototypeOf(old)); 
  for (const key of Object.keys(old)) { 
    result[key] = (<any> old)[key]; 
  } 
  for (const key of Object.keys(changes)) { 
    result[key] = (<any> changes)[key]; 
  } 
  return result; 
} 

Next, we will create a function for working with Math.random. randomInt will return a random integer in a certain range ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required