Last active
May 19, 2018 07:37
-
-
Save kuldeepkeshwar/f2f9f94153c7649c223675e42fcd0cda to your computer and use it in GitHub Desktop.
implementing for-of loop
This file contains hidden or 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
// implementation of "for of loop" | |
function forOf(iterable,callback){ | |
var iterator = iterable[Symbol.iterator](); | |
var result=iterator.next(); | |
var index=0; | |
while(!result.done){ | |
callback(result.value,index); | |
result=iterator.next(); | |
index++; | |
} | |
} | |
// custom Iterable object | |
class Users { | |
constructor(users){ | |
this.users=users; | |
} | |
[Symbol.iterator](){ | |
var index=0; | |
var len= this.users.length; | |
var result=null; | |
return { | |
next:()=>{ | |
result={value:this.users[index],done:!(index<len)} | |
index++; | |
return result; | |
} | |
} | |
} | |
} | |
const names = ['John', 'Mary', 'Christine', 'Edward', 'James']; | |
const users = new Users(names); | |
forOf(users,(user)=>{ | |
console.log('using forOf :',user); | |
}) | |
for (let user of users) { | |
console.log('using for-of-loop : ',user); | |
} | |
console.log('using spread operator:', ...users) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment