Created
April 6, 2022 14:09
-
-
Save ErickWendel/68e773fbb2aa73dc3e70803e82464bf5 to your computer and use it in GitHub Desktop.
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
// not iterable | |
{ | |
const myItem = { | |
a: 1, | |
b: 2 | |
} | |
// const r = [...myItem] // TypeError: myItem is not iterable | |
} | |
// now object is iterable | |
{ | |
const myItem = { | |
a: 1, | |
b: 2, | |
*[Symbol.iterator]() { | |
for (const field of Object.entries(myItem)) | |
yield field | |
} | |
} | |
const objectToEntries = [...myItem] | |
console.log('object to Array from iterable', objectToEntries) | |
// [ [ 'a', 1 ], [ 'b', 2 ] ] | |
console.log('object to Map from iterable ', new Map(myItem)) | |
// Map(2) { 'a' => 1, 'b' => 2 } | |
} | |
console.log('\n--------------------------------\n') | |
console.log('*working with function\'s arguments*\n') | |
function myFunction(message, arg1, arg2, arg3, arg4, arg5) { | |
console.log(`message [${message}] - received [${arg1} ${arg2} ${arg3} ${arg4}, ${arg5}]`) | |
} | |
// object not iterable | |
{ | |
const data = { | |
message: 'using Object.values manually', | |
firstArg: 'a', | |
secondArg: 'b', | |
thirdArg: 'c', | |
forthArg: 'd', | |
fifthArg: 'e', | |
values: () => Object.values(data), | |
} | |
myFunction(...data.values()) | |
// message [using Object.values manually] - received [a b c d, e] | |
} | |
// object iterable | |
{ | |
const data = { | |
message: 'using Symbol.iterator', | |
firstArg: 'a', | |
secondArg: 'b', | |
thirdArg: 'c', | |
forthArg: 'd', | |
fifthArg: 'e', | |
*[Symbol.iterator]() { | |
for (const field of Object.values(data)) | |
yield field | |
} | |
} | |
myFunction(...data) | |
// message [using Symbol.iterator] - received [a b c d, e] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment