Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Estruturas de Dados na Prática

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
Tweet

More Decks by Carlos Souza

Other Decks in Technology

Transcript

  1. Estruturas de dados, Sistemas de tipos (type systems) e como

    escrever JavaScript "that doesn't suck".
  2. 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*.
  3. let names = ["Sam", "Tyler", "Brook"]; let temperatures = [90,

    89, 88, 87]; Arrays - Criando // tudo é string // tudo é número
  4. Arrays - Misturando Tipos let radioStations = [95.5, "Jovem Pan

    94.70"]; // misturando números e strings
  5. 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
  6. 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];
  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"];
  8. 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
  9. 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
  10. 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}]
  11. 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
  12. 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){ //... }
  13. 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 }, ];
  14. ...e um pouco mais do que isso Arrays, Objects, Maps,

    and Sets Arrays Coleção de elementos
  15. 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"];
  16. 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" }; 

  17. 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();
  18. 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"]
  19. 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"] );
  20. 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
  21. 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();
  22. 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();
  23. 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();
  24. Array - Aceita valores repetidos let tags = []; tags.push(

    "JavaScript" ); tags.push( "Web" ); tags.push( "Web" ); tags.length; // 3
  25. 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
  26. 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
  27. 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
  28. WeakSets - Criando TypeError: Invalid value 
 used in weak

    set let tags = new WeakSet(); tags.add( { version: "2015" } ); tags.add( "JavaScript" );
  29. 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
  30. 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 );
  31. 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!
  32. Carlos Souza 
 Code School Estruturas de Dados Na Prática

    @caike https://www.flickr.com/photos/xtyler/3108575590