diff --git a/Week-4/ES6/Symbols/symbols.challenge.js b/Week-4/ES6/Symbols/symbols.challenge.js new file mode 100644 index 0000000..5b59ef4 --- /dev/null +++ b/Week-4/ES6/Symbols/symbols.challenge.js @@ -0,0 +1,38 @@ +const CARCOLOR = Symbol(); // give red and no see changes in below console +const CARMAKE = Symbol(); +const CARMODEL = Symbol(); + +class Car { + constructor(color, make, model) { + this[CARCOLOR] = color; + this[CARMAKE] = make; + this[CARMODEL] = model; + } + set color(color){ + this[CARCOLOR] = color; + } + set model(model){ + this[CARMODEL] = model; + } + set make(make){ + this[CARMAKE] = make; + } + get color() { + return this[CARCOLOR]; + } + get model() { + return this[CARMODEL]; + } + get make() { + return this[CARMAKE]; + } +} +let myCar = new Car('Red', 'Porsche', 'Cayanne'); +console.log(myCar); +myCar.color = `black`; +myCar.make = `Jaguar`; +myCar.model = `Land Rover`; +console.log(myCar); + +// implement the functionality to set and get values to car color - Black, car model - Land Rover and car maker - Jaguar +// you should assign values to those private variables inside class - use setter and getter methods diff --git a/Week-4/ES6/Symbols/symbols.example.js b/Week-4/ES6/Symbols/symbols.example.js new file mode 100644 index 0000000..b83969d --- /dev/null +++ b/Week-4/ES6/Symbols/symbols.example.js @@ -0,0 +1,67 @@ +// console.log(typeof(true)); +// console.log(typeof(null)); +// console.log(typeof(undefined)); +// console.log(typeof(2)); +// console.log(typeof(`a`)); +// console.log(typeof({})); + +// new Datatype - symbols - a primitive datatype - a SYMBOL is something which is an identifier, +// symbols provide totally unique something that we can assign to variables, symbol is not a constructor, +// we can not so new Symbol(), it's just like a string + +// const string1 = String('Hello'); +// const string2 = "Hello"; + +// console.log(string1); +// console.log(string2); + +// const aSymbol = Symbol(); +// console.log(aSymbol); + +console.log(Symbol() === Symbol()) + +// symbols are used to avoid name collisions in properties of an object +// we can't guarantee normally with property names specifically in objects +// or more specifically in constructors and classes that a property name is actually private that it can't get messed with + +const a = Symbol(); +const b = Symbol(); + +console.log(a===b); // it yields false because they both reference different w=even if they look same and alike +// because we are comparing a random value with another random, symbols will guarantee that one Symbol can never get get used again + +/* +class Car { + constructor (color, make, model) { + this.color = color; + this.make = make; + this.model = model; + } +} + +let myCar = new Car('Red', 'Porsche', 'Cayanne'); +console.log(myCar); +myCar.color = `blue`; +console.log(myCar); +*/ + +const CARCOLOR = Symbol(); // give red and no see changes in below console +const CARMAKE = Symbol(); +const CARMODEL = Symbol(); + +// console.log(CARCOLOR, CARMAKE, CARMODEL) + +class Car { + constructor(color, make, model) { + this[CARCOLOR] = color; + this[CARMAKE] = make; + this[CARMODEL] = model; + } +} + +let myCar = new Car('Red', 'Porsche', 'Cayanne'); +console.log(myCar); +myCar.color = `blue`; +console.log(myCar.color); +// console.log(myCar); +// console.log(Symbol.for(`test`) === Symbol.for(`test`)) \ No newline at end of file diff --git a/Week-4/ES6/iterators & generators/generators.html b/Week-4/ES6/iterators & generators/generators.html new file mode 100644 index 0000000..b36d33f --- /dev/null +++ b/Week-4/ES6/iterators & generators/generators.html @@ -0,0 +1,17 @@ + + + \ No newline at end of file diff --git a/Week-4/ES6/iterators & generators/iterators_generators_example.js b/Week-4/ES6/iterators & generators/iterators_generators_example.js new file mode 100644 index 0000000..22dd5c3 --- /dev/null +++ b/Week-4/ES6/iterators & generators/iterators_generators_example.js @@ -0,0 +1,12 @@ +function* aGenerator(){ + for(let i=0;i<10;i++){ + console.log("I just ran"); + yield ; //PAUSE HERE + console.log("I ran too"); + } +} +const gen = aGenerator(); +console.log(gen.next('aman')); +console.log(gen.next()); +console.log(gen.next()); +console.log(gen.next()); diff --git a/Week-4/ES6/readme.md b/Week-4/ES6/readme.md new file mode 100644 index 0000000..e69de29 diff --git a/Week-4/ES6/static methods/staticmethods.example.js b/Week-4/ES6/static methods/staticmethods.example.js new file mode 100644 index 0000000..e648564 --- /dev/null +++ b/Week-4/ES6/static methods/staticmethods.example.js @@ -0,0 +1,54 @@ +// function superhero(name, strength, speed) { +// this.name = name; +// this.strength = strength; +// this.speed = speed; +// } +// superhero.prototype.goodHero = true; +// superhero.prototype.powerUp = function(){ +// this.strength +=5; +// } +// let hero1 = new superhero("Hulk", 10, 5); +// console.log(hero1); +// hero1.powerUp(); +// console.log(hero1); + +//ES6 implementation + +class superhero { + constructor(name, strength, speed) { + this._name = name; + this._strength = strength; + this._speed = speed; + this.goodHero = true; // focus on this + } + powerUp(){ + this._strength += 5; + } + get name(){ + console.log(" name"+this._name); + } + set name(newname){ + this._name = newname; + } + static goodHero(){ + return true; + } +} + +const hulkdetails = ["Hulk", 10, 5]; +const bulkdetails = ["Bulk", 10, 5]; + +let hero1 = new superhero(...hulkdetails); +// console.log(hero1.name); +// console.log(hero1) +// +// hero1.powerUp(); +// hero1.powerUp(); +// hero1.powerUp(); +// console.log(hero1) + +let hero2 = new superhero(...bulkdetails); +console.log(superhero.goodHero()) + +// hero1.name = "george"; +console.log(hero1) diff --git a/Week-4/ES6/subclass/subclass.challenge.js b/Week-4/ES6/subclass/subclass.challenge.js new file mode 100644 index 0000000..0d23abe --- /dev/null +++ b/Week-4/ES6/subclass/subclass.challenge.js @@ -0,0 +1,73 @@ + +// inheritance - subclasses + +//implement methods in subclass (Human) which will override parent class functionality + +//1. implement a custom function which will add "Mr" to name property in subclass +//2. implement a method in subclass which will increment the power by 2 +//3. implement a method in subclass to reduce the power by half +//4. add 2 more properties to Human class - city and state (private to human class) +class superhero { + constructor(name, strength, speed) { + this._name = name; + this._strength = strength; + this._speed = speed; + // this.goodHero = true; // focus on this + } + powerUp() { + this.strength += 5; + } + get name() { + return this._name; + } + get strength() { + return this._strength; + } + get speed() { + return this._speed; + } + set name(newname) { + this._name = newname; + } + + static goodHero() { + return true; + } +} + +class Human extends superhero { + constructor(healthpoints,city,state,...superherostuff) { + super(...superherostuff); + this._healthpoints=healthpoints; + this._city = city; + this._state = state; + } + get healthpoints() { + console.log("get healthh"); + return this._healthpoints; + } + set healthpoints(healthpoints) { + this._healthpoints = healthpoints; + } + get name() { + return `Mr ${this._name}` ; + } + set name(newname){s + this._name=newname + } + + editName = () => { + this._name = `Mr ${this._name}`; +} +powerUp = () =>{ + this._strength += 2; +} +speedDown = () => { + this._speed /= 2; +} +} +const details = [20,"unnao","uttar pradesh","Bill", 10, 8]; +var hero3 = new Human(...details); +console.log(hero3.name); +hero3.name='abcd'; +console.log(hero3.name) \ No newline at end of file diff --git a/Week-4/ES6/subclass/subclass.example.js b/Week-4/ES6/subclass/subclass.example.js new file mode 100644 index 0000000..eba2fd9 --- /dev/null +++ b/Week-4/ES6/subclass/subclass.example.js @@ -0,0 +1,37 @@ +// inheritance - subclasses +class superhero { + constructor(name, strength, speed) { + this._name = name; + this._strength = strength; + this._speed = speed; + // this.goodHero = true; // focus on this + } + powerUp() { + this.strength += 5; + } + get name() { + console.log("get name"); + return this._name; + } + set name(newname) { + this._name = newname; + } + static goodHero() { + return true; + } +} + +class Human extends superhero{ + constructor(healthpoints, ...superherostuff){ + super(...superherostuff); + this._healthpoints = healthpoints; + } + +} +const details = [20,"Bill",10,8] +const hero3 = new Human(...details); +console.log(hero3); +hero3.name = "sai"; +console.log(hero3) +const hero4 = new superhero(20,"abc", 8); +console.log(hero4); diff --git a/Week-4/ES6/tagged_templates/index.html b/Week-4/ES6/tagged_templates/index.html new file mode 100644 index 0000000..69db53c --- /dev/null +++ b/Week-4/ES6/tagged_templates/index.html @@ -0,0 +1,6 @@ + + +
+ + + \ No newline at end of file diff --git a/Week-4/ES6/tagged_templates/tagged_template.challenge.js b/Week-4/ES6/tagged_templates/tagged_template.challenge.js new file mode 100644 index 0000000..f40c5db --- /dev/null +++ b/Week-4/ES6/tagged_templates/tagged_template.challenge.js @@ -0,0 +1,35 @@ +//With the template provided, write a template tag that will validate an SQL statement: +//Only SELECT or UPDATE statements are valid - write validation logic which allows only SELECT, UPDATE +//The passwords table cannot be altered +//there is no order by clause, add it and order by asc +// When done, return the reconstructed query or a note any errors + +let city = `Chicago` //data we got from somewhere else (api or database) +let userId = 3; //data we got from somewhere else (api or database) +let command = `SELECT *`; +let table = `USERS`; +let whereClauses = [ + `uid = ${2+1}`, + `OR city = ${city}` +] +function checkQuery(identifiers,...variables) { + let finalQuery = ""; + const queryType = variables[0].split(" ")[0]; + const table = variables[1]; + if(queryType == "UPDATE" && table == "PASSWORDS"){ + console.log("You can not change password table"); + return finalQuery; + } + if(queryType == 'UPDATE' || queryType == 'SELECT'){ + finalQuery = (order) ? (`${variables[0]} FROM ${table} WHERE ${variables[2][0]} ${variables[2][1]} ORDER BY city`) : (`${variables[0]} FROM ${table} WHERE ${variables[2][0]} ${variables[2][1]} ORDER BY city asc`); + return finalQuery; + } else{ + console.log("only update and select query can be processed"); + return finalQuery; + } +} +var query = checkQuery `${command} FROM ${table} WHERE ${whereClauses} ${order}`; +console.log(query); +// Your code to call the tag and log the return value here... +// your output should be - SELECT * FROM USERS WHERE uid = 3 OR city = chicago ORDER BY asc +// Spread syntax is a more common and easy here if you are comfortable with it diff --git a/Week-4/ES6/tagged_templates/tagged_templates.example.js b/Week-4/ES6/tagged_templates/tagged_templates.example.js new file mode 100644 index 0000000..a0f6826 --- /dev/null +++ b/Week-4/ES6/tagged_templates/tagged_templates.example.js @@ -0,0 +1,73 @@ +let line1 = "we are moving onto tagged templates, tagged templates are really popular but incredibly under served"; +let line2 = "there is less documentation available for this, initially we aren't sure why should we use it "; +let line3 = "once we got it down, it actually it is quite powerful, the use-cases are very limited"; + +let lines = [line1, line2, line3]; + +//Tagged templates +function buildHTML(param){ + console.log("it works", param); +} + +const result = buildHTML(3); +// console.log(result); + +const result2 = buildHTML`what's going on here`; +// console.log(result2); + +function build_HTML(strings, expressions) { + console.log(strings); + console.log(expressions); +} + + +// const result3 = build_HTML`
  • ${lines}
  • `; +// const result4 = build_HTML `
  • ${lines[0]}
  • `; + +// function build_HTML_new(strings, expression1, expression2) { +// console.log(strings); +// console.log(expression1); +// console.log(expression2); +// } +// const result5 = build_HTML_new `
  • ${lines[0]}${lines[1]}
  • `; + +function build_HTML_map(tags, lines) { + console.log(tags); + console.log(lines); + const newHtml = lines.map(function(line){ + return `${tags[0]}${line}${tags[1]}` + }); + return newHtml; +} +const result6 = build_HTML_map`
  • ${lines}
  • `; +console.log(result6); +// document.querySelector('#quotes').innerHTML = result6; + +// const output = buildHTML2`
  • ${lines}
  • `; +// output('#quotes'); +// function buildHTML2(tags, lines) { +// return function(element) { +// const newHTML = lines.map(function(line){ +// return `${tags[0]}${line}${tags[1]}` +// }); +// const finalHTML = newHTML.join(''); +// document.querySelector(element).innerHTML += finalHTML; +// } +// } + + + +function testFunction(){ + return "hello, from Refinitiv"; +} +const templateLiteralCallback1 = `Rob, ${() => testFunction()}`; +console.log(templateLiteralCallback1); + +const templateLiteralCallback2 = `Rob, ${testFunction()}`; +console.log(templateLiteralCallback2); + +function taggedcallback(strings, func) { + return strings[0] + func(); +} +const taggedLiteralcallback = taggedcallback`Rob, ${() => testFunction()}`; +console.log(taggedLiteralcallback); diff --git a/Week-4/ES6/template literals/template_literals.challenge.js b/Week-4/ES6/template literals/template_literals.challenge.js new file mode 100644 index 0000000..7c4fa0b --- /dev/null +++ b/Week-4/ES6/template literals/template_literals.challenge.js @@ -0,0 +1,15 @@ +// using template literals build a JS program to check if a person is eligible for a price discount or not +// check if +// if a registered member - discount is 5% +// if not registered member - discount is 4% +const users=['aman','vijay','bharath','gagan']; +function registeredMember(name){ + if(users.indexOf(name) !=-1){ + discount=5; + } else{ + discount=4; + } + return `discount is ${discount}%` +} +console.log(registeredMember('aman')); +console.log(registeredMember('xyz')); diff --git a/Week-4/ES6/template literals/template_literals.example.js b/Week-4/ES6/template literals/template_literals.example.js new file mode 100644 index 0000000..fed61a5 --- /dev/null +++ b/Week-4/ES6/template literals/template_literals.example.js @@ -0,0 +1,41 @@ +const name = "Rob"; +const hello = "hello" + name; +console.log(hello); + +const selectQuery = 'SELECT * FROM users WHERE name ="' + name + '" AND city = "' + name + '"'; +console.log(selectQuery); +//use Graveney ``, interchangable with '' and "", it gives the string some more power +const tryit = `hello, ${name}`; +console.log(tryit); + +const name1 = "Javascript"; +const city = "Hyderabad"; + +const selectQuery1 = `SELECT * from users WHERE name = "${name1}" AND city = "${city}"`; +console.log(selectQuery1); + +//Multi line feature +// const string = "Yesterday was a rainy day, +// lot of traffic" +const string1 = "Yesterday was a rainy day,"+ +"lot of traffic"; +console.log(string1); + +const string2 = "Yesterday was a rainy day, \n" + + "lot of traffic"; +console.log(string2); + +const string3 = `Yesterday was a rainy day, + lot of traffic`; +console.log(string3); + +const newHTML = ` +
    +${name} +
    ` + +console.log(newHTML); + +//Expressions +const anExpression = `43 ** 23 = ${43*23}`; +console.log(anExpression); diff --git a/Week-4/ES7/Exponentiation/Exponentiation.example.js b/Week-4/ES7/Exponentiation/Exponentiation.example.js new file mode 100644 index 0000000..1cc131f --- /dev/null +++ b/Week-4/ES7/Exponentiation/Exponentiation.example.js @@ -0,0 +1,61 @@ +const x = 2 * 2 * 2 * 2 * 2; +console.log(x); + +const x2 = 2 ** 5; + +const a = 3 ** 2.5; + +const b = 100* -1; + +const d = 2 ** 3 ** 4; + +const e = (2 ** 3) ** 4; +const f = 2 ** (3 ** 4); +console.log(d , e ,f); + + +// includes is essentially same as indexof except it returns a boolean + +// const arr = [1,2,3,4,5]; +// if(arr.indexOf(22)> -1) { +// console.log("found"); +// } else { +// console.log("not found"); +// } + +// const inArr = arr.includes(2); +// console.log(inArr); + +//indexof uses strict comparision, compares with every single value internally + +console.log(NaN === NaN) + +const arr = [1, 2, 3, 4, 5, NaN]; +if (arr.indexOf(NaN) > -1) { + console.log("found"); +} else { + console.log("not found"); +} + +const inArr = arr.includes(NaN); +console.log(inArr); + +// destructuring rest paramaters + +const someJSON = { + name: "Wayne Rooney", + position: "Forward", + club: "Manchester United" +} + +const {name, position, club} = someJSON; + +console.log(name, position, club); + +function sum(...array) { + return array.reduce((number, total) => { + return number + total; + }) +} + +console.log(sum(1,4,7,3)); diff --git a/Week-4/ES7/readme.md b/Week-4/ES7/readme.md new file mode 100644 index 0000000..2dac7aa --- /dev/null +++ b/Week-4/ES7/readme.md @@ -0,0 +1,7 @@ +3 new additions + exponentiation operator + includes methods for arrays and typed arrays + destructure for rest parameters +2 deletions + removed enumerate from proxy handler + generators and their methods are not constructable anymore \ No newline at end of file diff --git a/Week-4/ES8/Proxy_Constructors/proxy_constructor.challenge.js b/Week-4/ES8/Proxy_Constructors/proxy_constructor.challenge.js new file mode 100644 index 0000000..ad1987e --- /dev/null +++ b/Week-4/ES8/Proxy_Constructors/proxy_constructor.challenge.js @@ -0,0 +1,76 @@ +// 1. SET +// Rewrite the sample code below so that every time a property is set a callback runs. +// your callback will check if the property changed is employees. + +//If it is employees, make sure if it is an Array, a string or null. +//If anything else comes, respond with an appropriate message +//If not employees, let it pass + +let manager = { + office: `Dubai`, + dept: `sales`, + employees: 0 +} +let handler = { + get: (target, propName) => { + return target[propName]; + }, + set: (target, propName, newVal) => { + if(propName==='employees'){ + if(newVal.isArray|| typeof newVal === 'string' || newVal instanceof String || newVal== null){ + target[propName] = newVal; + } else{ + console.log("its not allowed to have manager with value other than array,string or null"); + } + } else{ + target[propName] = newVal; + } + } +} +let newObj = new Proxy(manager, handler); +manager.office = `London` //updates +manager.employees = ['Jim', 'Patrick', 'Mary']; //updates +manager.employees = 3; // doesn't update +manager.employees = null; // updates +manager.employees = {name:'Jim'} // doesn't update + +// 2. GET +// adjust the following code so that anytime an internal object with accessLevel of 1 is accessed, +//"Access Denied" is returned. +const obj={username:'Access denied' ,accessCode:'Access denied' ,accessLevel:'Access denied' }; +const user = [ + { + username: `bob`, + accessLevel: 1, + accessCode: 1234 + }, + { + username: `Mary`, + accessLevel: 2, + accessCode: 2345 + }, + { + username: `Harold`, + accessLevel: 2, + accessCode: 9999 + } +] + +let handlerTwo = { + get: (target, propName) => { + if(target[propName].accessLevel!==1){ + return target[propName]; + } else{ + return obj; + } + }, + + set: (target, propName, newVal) => { + target[propName] = newVal; + } +} +users = new Proxy(user, handlerTwo); +console.log(users[0].username) // Access Denied +console.log(users[0].accessCode) // Access Denied +console.log(users[1].accessCode) // 2345 +console.log(users[2].username) // Harold diff --git a/Week-4/ES8/Proxy_Constructors/proxy_constructor.example.js b/Week-4/ES8/Proxy_Constructors/proxy_constructor.example.js new file mode 100644 index 0000000..296023e --- /dev/null +++ b/Week-4/ES8/Proxy_Constructors/proxy_constructor.example.js @@ -0,0 +1,108 @@ +// proxy constructor and can be invoked with new - allows us to re-architecture our code +// proxy in english is a middle man +// ex: Microsoft stock +// proxy constructor allows us to cut off almost any part of object change process +// this is new because all of this stuff happens internally and we can't see it by any hooks +// and hence we are creating a middleware (traps!!)- ex: express.js +// using ths we can hijack get, set processes - intercept +// not same as setters and getters in class system, they work little bit different +// API exposes get set has construct etc - total 13 methods +// getPropertyOf() +// setPropertyOf() +// isExtensible() +// preventExtensions() +// getOwnPropertyDescriptor() +// defineProperty() +// deleteProperty() +// has() +// get() +// set() +// ownKeys() +// apply() +// construct() + +// tis gives exclusive control over objects - to get and set +// validations +// logic / Middleware + +//proxy is a constructor and takes 2 args +// 1. Object to proxy and 2. Object serving as the handler + +let handler = { + // this has all the above properties to trap + // get trap // takes 2 args - target object and the property asked for + get: (target, propName) => { + // console.log(target, propName); + //return undefined; + return target[propName]; + }, + // set takes 3 args - target obj, property and new val of property + set: (target, propName, newVal) => { + console.log(target, propName, newVal); + target[propName] = newVal; + }, + // has: (target, propName) => { + // // we can use reflex here - pending for next + // console.log("check"); + // } +} + +let newObj = new Proxy({}, handler); +newObj.name = "rob"; +newObj.job = "Instructor"; +console.log(newObj.name); // WHAT'S GOING ON HERE?? WHY UNDEFINED?? +console.log(newObj.job); +newObj.age = 99; +console.log(newObj.age); // change the get-return part to send something for age property too +console.log(newObj); + +// if("name" in newObj) { +// console.log("I found it!!"); +// } + +// restrict user to set non-numeric values for age +// check if the property is existed in object + + +// ---------- another example + +// class Car { +// constructor(make, model) { +// this.make = make; +// this.model = model; +// } +// printInfo() { +// console.log(this.make, this.model); +// } +// } + +// let handler1 = { +// get: (target, propName) => { +// console.log(`someone is trying to access ${propName} property`) +// } +// } + +// let myCar = new Car(`toyota`, `camry`); +// let carProxy = new Proxy(myCar, handler1); +// console.log(carProxy.make); + + +// --------------------- another example --------------- + +function sum (x,y){ + console.log("sum"); + return x+y; +} + +let handler2 = { + //apply trap takes 3 args - target, the this, argumentlist + apply: (target, thisArg, argsList) => { + console.log(argsList); + return target(argsList[0], argsList[1]) * 100 + } +} + +const sumProxy = new Proxy(sum, handler2); + +console.log(sum(2,3)); +console.log(sumProxy(2, 3)); diff --git a/Week-4/ES8/Reflect/reflect.challenge.js b/Week-4/ES8/Reflect/reflect.challenge.js new file mode 100644 index 0000000..f0d12f2 --- /dev/null +++ b/Week-4/ES8/Reflect/reflect.challenge.js @@ -0,0 +1,22 @@ +let course = {}; +course.trainer='nagasai' +if(Reflect.defineProperty(course, 'name', {value: 'Javascript',writable: false})){ + console.log('property created!'); +} else{ + console.log('property not created!'); +} +if(Reflect.defineProperty(course, 'duration', {value: '3 hours',writable: false})){ +console.log('property duration created!'); +}else{ + console.log('property duration not created!'); +} +console.log(course); +Reflect.deleteProperty(course, 'trainer'); +console.log(course); +console.log(Reflect.getOwnPropertyDescriptor(course, 'duration').value); +console.log(Reflect.getOwnPropertyDescriptor(course, 'name').value); + +// use reflect API to define property, delete a property, getOwnpropertydescriptor details +// property to define - name with value as "Javascript", make it read only (writable : false) +// property to define - duration with value as "3 hours", make it read only (writable : false) +// getOwnpropertydescriptor - check and print metadata about name property diff --git a/Week-4/ES8/Reflect/reflect.example.js b/Week-4/ES8/Reflect/reflect.example.js new file mode 100644 index 0000000..ba9ca8a --- /dev/null +++ b/Week-4/ES8/Reflect/reflect.example.js @@ -0,0 +1,77 @@ +// Reflection is to examine, introspect or modify your program at run-time +// Reflect and proxy both go hand in hand +// Reflect can't be instantiated and invoked +// Reflect is a standalone global Object than has methods that are 1:1 with proxy handlers + +// Standalone global Object - Math() - math is a static object with whole bunch of static methods +// static methods - they wnt attached to the instance but they are attached to class + +// console.log(new Reflect()); + +// Reflect.get() takes 2 properties +// 1. target, 2.property + +const x = { + a:1, b:2 +} + +console.log(Reflect.get(x, `a`)); +console.log(x[`a`]); + +const arr = ["joe", "akash", "mary"]; +console.log(arr[0]) +console.log(Reflect.get(arr,0)); + + +const monster1 = { + secret: 'secret', + counter: 4 +}; + +const handler1 = { + get: function (target, prop, receiver) { + if (prop === 'secret') { + return `You can't access secret`; + } else { + //console.log(Reflect.get(target, prop, receiver)) + // arguments[0][prop] + return Reflect.get(...arguments); + //fast and easy way, the win with reflect here is very explicit + //and we are accessing something inside a variable + } + } +}; + +const proxy1 = new Proxy(monster1, handler1); + +console.log(proxy1.counter); +// expected output: 4 + +console.log(proxy1.secret); + +// ---------------- reflect.has +// works as hasownproperty and in + +const obj = { + number : 22 +} + +console.log(obj.hasOwnProperty('number')); +console.log('number' in obj); +console.log(Reflect.has(obj, 'number')); + +// ---------------reflect.apply +function sum(...array) { + return array.reduce((number, total)=> { + return number + total; + }) +} +// sum.apply = function(){ +// throw new Error('I broke apply function!'); +// } +console.log(sum[1,2,3]); +console.log(sum.apply(null, [1,2,3])); +console.log(Function.apply.call(sum, null, [1,2,3])); +console.log(Reflect.apply(sum, null, [1, 2, 3])); + +// if proxy provides traps to change objects, Reflect provides introspection to get data about objects diff --git a/Week-4/ES9/Bonus-async-await/async-awaitexample.js b/Week-4/ES9/Bonus-async-await/async-awaitexample.js new file mode 100644 index 0000000..5dd36e8 --- /dev/null +++ b/Week-4/ES9/Bonus-async-await/async-awaitexample.js @@ -0,0 +1,19 @@ +function doubleAfter2Seconds(x) { + return new Promise(resolve => { + setTimeout(() => { + resolve(x * 2); + }, 2000); + }); +} + +async function addAsync(x) { + const a = await doubleAfter2Seconds(10); + const b = await doubleAfter2Seconds(20); + const c = await doubleAfter2Seconds(30); + return x + a + b + c; +} + + +addAsync(10).then((sum) => { + console.log(sum); +}); diff --git a/Week-4/ES9/rest & spread for objects/rest_spread_example.js b/Week-4/ES9/rest & spread for objects/rest_spread_example.js new file mode 100644 index 0000000..65ebf21 --- /dev/null +++ b/Week-4/ES9/rest & spread for objects/rest_spread_example.js @@ -0,0 +1,69 @@ +const user = { + firstName: "Nagasai", + lastName: "P", + session: "Javascript", + city: "Hyderabad", + state: "telangana" +} + +//how to create a new object without city property + +const {...newuser} = user; +console.log(newuser); +delete newuser.city +console.log(newuser); + +// const {firstName, lastName, session, state} = user +// console.log(firstName); + +// const {city, ...newuser2} = user; +// console.log(newuser2); + +// const { +// city, +// state, +// ...newuser3 +// } = user; +// console.log(newuser3); + +// ----------------- Regular Expressions + +// const theMatch = "Javascript is Awesome".match(/(Javascript)?.+(Awesome)/i) +// console.log(theMatch); +// const matchedString = theMatch[0]; +// const language = theMatch[1]; +// const experience = theMatch[2]; +// console.log(matchedString, language, experience); + +// const theMatch = "is Awesome".match(/(Javascript)?.+(Awesome)/i) + +const RE_DATE = /(?[0-9]{4})-(?[0-9]{2})-(?[0-9]{2})/; + +const matchObj = RE_DATE.exec('1999-12-31'); +const year = matchObj.groups.year; // 1999 +const month = matchObj.groups.month; // 12 +const day = matchObj.groups.day; // 31 + +console.log(year, month, day); + +// ----------------- Async iterators + +const names = ['tyepescript', 'babel', 'traceur'] + +// for(let i=0; i< names.length; i++) { +// console.log(names[i]) +// } + +// for(key in names) { +// console.log(names[key]) +// } + +// names.forEach(name => { +// console.log(name); +// }) + +// for of interface is an iterable and doesn't know anything about array or object +for (name of names) { + console.log(name) +} +