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

Since we will work a lot with arrays, we can use some utility functions. First, we create a function that flattens a two dimensional array into a one dimensional array:

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

Next, we create a function that replaces a single element of an array with a specified value. We will use functional programming in this chapter again, so we must use immutable data structures. We can use map for this, since this function provides both the element and the index to the callback. With this index, we can determine whether that element should be replaced:

export function arrayModify<U>(array: U[], index: number, newValue: U) { return array.map((oldValue, currentIndex) ...

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