Share
Embed
Estruturas de Dados na Prática
Esta palestra aborda estruturas de dados nativas do JavaScript e como podemos usá-las de forma a escrever código mais eficiente. Apresentada no CEJS em Fortelza, Ceará.
Carlos Souza
May 13, 2017
Transcript
56 slides
-
Estruturas de dados, Sistemas de tipos (type systems) e como
escrever JavaScript "that doesn't suck". -
Estruturas de Dados * da melhor maneira possível e com
o menor desperdício de tempo e esforço. como organizar dados de forma a serem usados de maneira eficiente*. -
let names = ["Sam", "Tyler", "Brook"]; let temperatures = [90,
89, 88, 87]; Arrays - Criando // tudo é string // tudo é número -
Arrays - Misturando Tipos let radioStations = [95.5, "Jovem Pan
94.70"]; // misturando números e strings -
Arrays - Misturando Tipos let activeUsers = ["Sam", 10, "Tyler",
15]; // misturando números e strings -
Quando dá erro // misturando números e strings let radioStations
= [101.1, 98.1, "Jovem Pan 94.70", 107.7]; let minAndMax = findMinAndMax( radioStations ) console.log( minAndMax ); // [98.1, 107.7]; console.log( parseFloat("94.70") ); // 94.70 console.log( parseFloat("Jovem Pan 94.70") ); // NaN -
Lembra aquele erro ? // misturando números e strings let
radioStations = [101.1, 98.1, "Jovem Pan 94.70", 107.7]; let minAndMax = findMinAndMax( radioStations ) console.log( minAndMax ); // [98.1, 107.7]; -
// use sempre números let radioStations = [101.1, 98.1, 80.2,
107.7]; Arrays - Criando // ou sempre strings let radioStations = ["101.1", "98.1", "80.2", "107.7"]; let minAndMax = findMinAndMax( radioStations ) console.log( minAndMax ); // [80.2, 107.7]; let minAndMax = findMinAndMax( radioStations ) console.log( minAndMax ); // ["80.2", "107.7"]; -
Arrays - Lendo // Acessando via index let names =
["Sam", "Tyler", "Brook"]; console.log( names[0] ); // Sam console.log( names[1] ); // Tyler console.log( names[2] ); // Brook // Destructuring let [first] = names; console.log( first ); // Sam let [first, second] = names; console.log( first, second ); // Sam Tyler -
Arrays - Lendo // Array Destructuring + Rest Parameters let
names = ["Sam", "Tyler", "Brook"]; let [first, ...theRest] = names; console.log( first, theRest ); // Sam ["Tyler", "Brook"] // for...of for(let name of names){ console.log( name ); // Sam } // Tyler // Brook -
Arrays - Lendo let gitQuestions = [ { command: "git
co quick-bug-fix", points: 10 }, { command: "git log -p app.js" , points: 15 }, ]; let [firstQ, ...theRestQ] = gitQuestions; console.log( firstQ, theRestQ ); // {"command":"git co quick-bug-fix","points":10} // [{"command":"git log -p app.js","points":15}] -
Arrays - Lendo let gitQuestions = [ { command: "git
co quick-bug-fix", points: 10 }, { command: "git log -p app.js" , points: 15 }, ]; for(let question of gitQuestions){ let command = question.command; let points = question.points; console.log( `command: ${command}\npoints: ${points}\n` ); } // command: git co quick-bug-fix // points: 10 // command: git log -p app.js // points: 15 -
Arrays - Lendo let gitQuestions = [ { command: "git
co quick-bug-fix", points: 10 }, { command: "git log -p app.js" , points: 15 }, ]; // Object Destructuring for(let question of gitQuestions){ let { command, points } = question; //... } for(let { command, points } of gitQuestions){ //... } -
Arrays - Dobrando as Regras gitQuestions.totalPoints = getTotalPoints(); for(let question
of gitQuestions){ console.log( question ); } // {"command":"git co quick-bug-fix","points":10} // {"command":"git log -p app.js","points":15} console.log( gitQuestions.totalPoints ); // 25 let gitQuestions = [ { command: "git co quick-bug-fix", points: 10 }, { command: "git log -p app.js" , points: 15 }, ]; -
...e um pouco mais do que isso Arrays, Objects, Maps,
and Sets Arrays Coleção de elementos -
Arrays, Objects, Maps, and Sets Objects Propriedades e comportamento Utilizados
de forma errada como key/value stores. -
Maps with objects is a bad idea let guitarReviews =
{}; let sg = { company: "Gibson", model: "SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; guitarReviews[strat]; // ["Bad", "Terrible", "Awful"]; guitarReviews[sg] = ["Good", "Great", "Excellent"]; guitarReviews[strat] = ["Bad", "Terrible", "Awful"]; guitarReviews[sg]; // ["Bad", "Terrible", "Awful"]; -
Maps with objects is a bad idea sg === strat
// false guitarReviews[sg] = ... toString(sg) toString(strat) // "[object Object]" // "[object Object]" keys(guitarReviews) // ["[object Object]"] toString(sg) === toString(strat) // true guitarReviews[strat] = ... let guitarReviews = {}; let sg = { company: "Gibson", model: "SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; -
Maps - Criando let sg = { company: "Gibson", model:
"SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; guitarReviews.set( sg, ["Good", "Great", "Excellent"] ) guitarReviews.set( strat, ["Bad", "Terrible", "Awful"] ); let guitarReviews = new Map(); -
Maps - Lendo let guitarReviews = new Map(); let sg
= { company: "Gibson", model: "SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; guitarReviews.set( sg, ["Good", "Great", "Excellent"] ) guitarReviews.set( strat, ["Bad", "Terrible", "Awful"] ); guitarReviews.get( strat ); // ["Bad", "Terrible", "Awful"] guitarReviews.get( sg ); // ["Good", "Great", "Excellent"] -
WeakMaps - Criando let guitarReviews = new WeakMap(); let sg
= { company: "Gibson", model: "SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; guitarReviews.set( sg, ["Good", "Great", "Excellent"] ); guitarReviews.set( strat, ["Bad", "Terrible", "Awful"] ); TypeError: Invalid value used as weak map key guitarReviews.set( "tele", ["Ok", "Decent"] ); -
WeakMaps - Lendo (more memory efficient for objs) let guitarReviews
= new WeakMap(); let sg = { company: "Gibson", model: "SG" }; let strat = { company: "Tonante", model: "Stratocaster" }; guitarReviews.set( sg, ["Good", "Great", "Excellent"] ); guitarReviews.set( strat, ["Bad", "Terrible", "Awful"] ); guitarReviews.get( sg ); // ["Good", "Great", "Excellent"] guitarReviews.get( strat ); // ["Bad", "Terrible", "Awful"] strat sg sempre use WeakMaps quando as keys forem objects garbage collector -
Map vs WeakMap // let map = new Map(); //
or // let map = new WeakMap(); const MAX_LOOP = 50000; function runBenchmark(){ for(let i=0; i < MAX_LOOP; i++){ let item = { number: i }; map.set( item, "item" ); } } runBenchmark(); -
Map vs WeakMap // let map = new Map(); //
or // let map = new WeakMap(); const MAX_LOOP = 100000; function runBenchmark(){ for(let i=0; i < MAX_LOOP; i++){ let item = { number: i }; map.set( item, "item" ); } } runBenchmark(); -
Map vs WeakMap // let map = new Map(); //
or // let map = new WeakMap(); const MAX_LOOP = 1000000; function runBenchmark(){ for(let i=0; i < MAX_LOOP; i++){ let item = { number: i }; map.set( item, "item" ); } } runBenchmark(); -
Array - Aceita valores repetidos let tags = []; tags.push(
"JavaScript" ); tags.push( "Web" ); tags.push( "Web" ); tags.length; // 3 -
let tags = new Set(); tags.add( "JavaScript" ); tags.add( "Web"
); tags.add( "Web" ); tags.size; // 2 Sets - Criando primitivos repetidos não são adicionados -
let tags = new Set(); tags.add( "JavaScript" ); tags.add( "Web"
); tags.add( "Programming" ); tags.add( { version: "2015" } ); tags.add( { version: "2015" } ); tags.size; // 5 Sets - Criando objetos repetidos são adicionados // não misture tipos -
Sets - Lendo let tags = new Set(); tags.add( "JavaScript"
); tags.add( "Web" ); tags.add( "Programming" ); // for...of for(let tag of tags){ console.log( tag ); // JavaScript } // Web // Programming // destructuring let [a,b,c] = tags; console.log( a, b, c ); // JavaScript Web Programming -
WeakSets - Criando TypeError: Invalid value used in weak
set let tags = new WeakSet(); tags.add( { version: "2015" } ); tags.add( "JavaScript" ); -
WeakSets - "Lendo" let guitars = new WeakSet(); let
sg = { model: "SG" }; let lesPaul = { model: "Les Paul" }; let nighthawk = { model: "Nighthawk" }; guitars.add( sg ); guitars.add( lesPaul ); guitars.has( sg ); // true guitars.has( lesPaul ); // true guitars.has( nighthawk ); // false lesPaul sg garbage collector -
WeakSets - "Lendo" na prática let sg = { model:
"SG" }; let lesPaul = { model: "Les Paul" }; let nighthawk = { model: "Nighthawk" }; let sold = new WeakSet(); sold.add( sg ); sold.add( lesPaul ); -
WeakSets - "Lendo" na prática sold guitar is it here
? is it here ? is it here ? guitar guitar let sg = { model: "SG" }; let lesPaul = { model: "Les Paul" }; let nighthawk = { model: "Nighthawk" }; let sold = new WeakSet(); sold.add( sg ); sold.add( lesPaul ); // checking against WeakSet if( sold.has(sg) ){ console.log( "sold" ); } if( !sold.has(nighthawk) ){ console.log( "not sold" ); } Immutable! -
Carlos Souza Code School Estruturas de Dados Na Prática
@caike https://www.flickr.com/photos/xtyler/3108575590