Created
January 30, 2021 23:56
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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