Skip to content

Instantly share code, notes, and snippets.

@Rolias
Created January 30, 2021 23:56
Show Gist options
  • Save Rolias/f4f874d0b533469fa56c8547e0ab10d9 to your computer and use it in GitHub Desktop.
Save Rolias/f4f874d0b533469fa56c8547e0ab10d9 to your computer and use it in GitHub Desktop.
Examples for medium article on using array .map() instead of a standard for loop
import * as faker from 'faker'
const MAX_COUNT = 10
const RADIX = 10
interface IdName {
id: string
name: string
}
function getFakeDataViaIndex(index: number): IdName {
return {
id: index.toString(RADIX),
name: faker.name.lastName(),
}
}
function getFakeData(): IdName {
return {
id: faker.random.uuid(),
name: faker.name.firstName(),
}
}
function getSomeTestDataForLoop(): IdName[] {
let data: IdName[] = []
for (let index = 0; index < MAX_COUNT; ++index) {
data.push(getFakeData())
}
return data
}
function getSomeTestDataMap(): IdName[] {
return [...Array(MAX_COUNT)].map(() => getFakeData())
}
const testData = getSomeTestDataForLoop()
console.log(`πŸ‘‰ Standard For:`, testData)
const testDataMap = getSomeTestDataMap()
console.log(`πŸ‘‰ Map:`, testDataMap)
const testDataIndexMap = [...Array(10).keys()].map(i => getFakeDataViaIndex(i + 1))
console.log(`πŸ‘‰ elements:`, testDataIndexMap)
// ==========================================================================
// a deeper look into the Array constructor
// ==========================================================================
const mt = new Array(5)
console.log(`πŸ‘‰ mt:`, mt)
const sameMt = Array(5)
console.log(`πŸ‘‰ sameMt:`, sameMt)
const notMt = [...new Array(5).keys()]
console.log(`πŸ‘‰ notMt:`, notMt)
console.log(`πŸ‘‰ :`, mt.toString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment