Skip to content

Instantly share code, notes, and snippets.

View ferreiratiago's full-sized avatar
🌍

Tiago Ferreira ferreiratiago

🌍
View GitHub Profile
@ferreiratiago
ferreiratiago / iterable-protocol.js
Created April 23, 2017 16:17
Iterable Protocol
const iterable = {
[Symbol.iterator](): iterator
}
@ferreiratiago
ferreiratiago / iterator-protocol.js
Created April 23, 2017 16:23
Iterator Protocol
const iterator = {
next() {
value: any,
done: boolean
}
}
@ferreiratiago
ferreiratiago / array-data-source-in-pratice.js
Created April 23, 2017 16:24
Array data source in pratice
const array = ['foo','bar','zed']
// Array is a data source because it implements an iterator.
console.log(typeof array[Symbol.iterator]) // function
// We first get the iterator which allow us to iterate (i.e. consume) over the array values.
const iterator = array[Symbol.iterator]()
// The iterator follows the protocol of being an object with the 'next' function.
console.log(typeof iterator.next) // function
@ferreiratiago
ferreiratiago / iterable-data-sources.js
Created April 23, 2017 16:26
Iterable data sources
// Arrays
for(let e of ['foo','bar']) {
console.log(e)
// 'foo'
// 'bar'
}
// Strings
for(let c of 'foo') {
console.log(c)
@ferreiratiago
ferreiratiago / hugo-plain-object-example.js
Created April 23, 2017 16:27
Plain object example (Hugo)
let Hugo = {
fullName: 'Hugo Matias',
toString() {
return `${this.fullName}`
}
}
@ferreiratiago
ferreiratiago / implement-iterables.js
Created April 23, 2017 16:27
Implement iterables example
const iterable = {
[Symbol.iterator]() {
let data = ['foo','bar']
return { // Iterator
next() {
return {
done: data.length === 0,
value: data.pop()
}
}
@ferreiratiago
ferreiratiago / iterator-as-iterable.js
Created April 23, 2017 16:28
Iterator as iterable
const iterable = {
data: ['foo','bar'],
next() {
return {
done: this.data.length === 0,
value: this.data.pop()
}
},
[Symbol.iterator]() {
// Return the iterable itself.
@ferreiratiago
ferreiratiago / why-iterator-as-iterable.js
Last active April 23, 2017 16:30
Why Iterator as Iterable
const array = ['foo', 'bar', 'zed']
const iterator = array[Symbol.iterator]()
for(let e of iterator) {
console.log(e)
break
// 'foo'
}
for(let e of iterator) {
@ferreiratiago
ferreiratiago / return-example.js
Created April 23, 2017 16:29
Return on Iterator
const iterable = {
done: false,
data: ['foo','bar','zed'],
next() {
done = this.done || this.data.length === 0
return done ?
// After 'return' is called the object returned by 'next' should also be done.
{
done: true
// We can ignore the 'value' when 'done' is 'true'.
@ferreiratiago
ferreiratiago / for-of-example.js
Created April 23, 2017 16:34
For-of data consumer example
for (let e of [1,2,3]) {
console.log(e)
// 1
// 2
// 3
}