├── README.md ├── condicionais ├── 01.js ├── 02.js ├── 03.js └── 04.js ├── extra ├── condicionais.js ├── funcoes.js ├── loops.js └── objetos.js ├── funcoes ├── 01.js └── 02.js ├── loops ├── 01.js └── 02.js └── objetos └── 01.js /README.md: -------------------------------------------------------------------------------- 1 | ### Exercícios para as aulas de Javascript I da turma 06 da {reprograma}. 2 | 3 | O objetivo dessa semana é entender os blocos básicos de construção com o Javascript: loops, condicionais, variáveis, objetos e funções. -------------------------------------------------------------------------------- /condicionais/01.js: -------------------------------------------------------------------------------- 1 | let a = 1 2 | let b = 2 3 | let c = 3 4 | 5 | // Resultado: "Hello, world!" 6 | if (6 < 2 * 5) { // 6 < 10 7 | console.log("Hello, world!") 8 | } 9 | 10 | // Resultado: 2222 11 | if (a > b && a > c) { // 1 > 2 && .. 12 | console.log(1111) 13 | } else { 14 | console.log(2222) 15 | } 16 | 17 | // Resultado: "*" 18 | if (a < c) { // 1 < 3 19 | console.log("*") 20 | } else if (a === b) { // não executa 21 | console.log("&") 22 | } else { // não executa 23 | console.log("$") 24 | } 25 | 26 | // Resultado: "####" 27 | if (a < b) { // 1 < 2 28 | console.log("####") 29 | } else { // não executa 30 | console.log("&&&&") 31 | } 32 | 33 | // Resultado: 100 200 0 34 | const x = 100 35 | const y = 200 36 | if (y <= 200 && x > 100) { // 200 <= 200 && 100 > 100 37 | console.log(`${x} ${y} ${x + y}`) 38 | } else { // não executa 39 | console.log(`${x} ${y} ${2 * x - y}`) 40 | } 41 | 42 | // Resultado: "*" 43 | if (a < c) { // 1 < 3 44 | console.log("*") 45 | } else if (a === c) { // não executa 46 | console.log("&") 47 | } else { // não executa 48 | console.log("$") 49 | } 50 | 51 | // a++ -> a = a + 1 52 | // Resultado: 1 3 4 53 | if (a++ > b++ || a-- > 0) { // 2 > 3 || 1 > 0 54 | c++ 55 | } else { // não executa 56 | c-- 57 | } 58 | console.log(`${a} ${b} ${c}`) 59 | 60 | // Resultado: "####" 61 | if (a < b) { // 1 < 3 62 | console.log("####") 63 | } else { // não executa 64 | console.log("&&&&") 65 | } 66 | 67 | // Resultado: "****" 68 | if (a < c) { // 1 < 4 69 | console.log("****") 70 | } else if (b > a) { // não executa 71 | console.log("&&&&") 72 | } else { // não executa 73 | console.log("####") 74 | } -------------------------------------------------------------------------------- /condicionais/02.js: -------------------------------------------------------------------------------- 1 | // Escreva a expressão em 2 | // Javascript que atribui o 3 | // valor `1` a `x` se `x` 4 | // for maior do que `y`. 5 | if (x > y) { 6 | x = 1 7 | } 8 | 9 | // Escreva a expressão em 10 | // Javascript que aumenta o 11 | // valor da variável `score` 12 | // em 5 unidades caso o valor 13 | // inicial de `score` esteja 14 | // entre 80 e 90. 15 | if (score >= 80 && score <= 90) { 16 | score += 5 // score = score + 5 17 | } 18 | 19 | // Reescreva a seguinte condicional 20 | // sem usar o operador `!`: 21 | // item = ! ( i < 10 || v >= 50 ) 22 | item = ( i < 10 || v >= 50 ) === false 23 | // ou... 24 | item = ( i >= 10 && v < 50 ) 25 | // refs: 26 | // - http://www.math.toronto.edu/preparing-for-calculus/3_logic/we_3_negation.html 27 | // - https://centraldefavoritos.com.br/2017/01/02/negacao-de-proposicoes/ (ver: "Negação de uma Proposição Disjuntiva") 28 | 29 | // Escreva a expressão em 30 | // Javascript que retorna `true` 31 | // se um número é par e `false` 32 | // se um número é impar. 33 | if (n % 2 === 0) { 34 | console.log(true) 35 | } else { 36 | console.log(false) 37 | } 38 | // ou ... 39 | if (n & 1 === 0) { 40 | console.log(true) 41 | } else { 42 | console.log(false) 43 | } 44 | // refs: 45 | // - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators 46 | // - https://code.tutsplus.com/articles/understanding-bitwise-operators--active-11301 (ver: "The & Operator") 47 | 48 | // Escreva a expressão em 49 | // Javascript que retorna `true` 50 | // se dois números forem positivos 51 | // e `false` se dois números 52 | // forem negativos. 53 | if (x > 0 && y > 0) { 54 | console.log(true) 55 | } else if(x < 0 && y < 0) { 56 | console.log(false) 57 | } 58 | 59 | // Escreva a expressão em 60 | // Javascript que retorna `true` 61 | // dois números tiverem os mesmo 62 | // sinal (+ / -) e `false` 63 | // se dois números tiverem sinais 64 | // diferentes. 65 | if (x > 0 && y > 0 || 66 | x < 0 && y < 0) { 67 | console.log(true) 68 | } else { 69 | console.log(false) 70 | } 71 | // ou... 72 | if (x > 0 && y > 0) { 73 | console.log(true) 74 | } else if (x < 0 && y < 0) { 75 | console.log(true) 76 | } else { 77 | console.log(false) 78 | } 79 | // ou... 80 | if (Math.sign(x) === Math.sign(y) && 81 | Math.sign(x) !== 0) { 82 | console.log(true) 83 | } else { 84 | console.log(false) 85 | } -------------------------------------------------------------------------------- /condicionais/03.js: -------------------------------------------------------------------------------- 1 | // Duas condicionais são equivalentes 2 | // quando, dado um mesmo input, devolvem 3 | // o mesmo output. Qual das próximas 4 | // condicionais são equivalentes? Porque? 5 | 6 | // Resposta: A == C, o B é diferente. 7 | 8 | // Porque... 9 | 10 | // rand = 1 11 | // A -> O valor é positivo: 1 12 | // B -> O valor é positivo: 1 && O valor é zero! 13 | // C -> O valor é positivo: 1 14 | 15 | // rand = 0 16 | // A -> O valor é zero! 17 | // B -> O valor é zero! 18 | // C -> O valor é zero! 19 | 20 | // rand = -1 21 | // A -> O valor é negativo: -1! 22 | // B -> O valor é negativo: -1! 23 | // C -> O valor é negativo: -1! 24 | 25 | // Gera um numero randomico entre -10 e 10. 26 | const rand = Math.floor(Math.random() * 21) - 10 27 | 28 | // A 29 | if (rand > 0) { 30 | console.log(`O valor é positivo: ${rand}!`) 31 | } else { 32 | if (rand < 0) { 33 | console.log(`O valor é negativo: ${rand}!`) 34 | } else { 35 | console.log(`O valor é zero!`) 36 | } 37 | } 38 | 39 | // B 40 | if (rand > 0) { 41 | console.log(`O valor é positivo: ${rand}!`) 42 | } 43 | if (rand < 0) { 44 | console.log(`O valor é negativo: ${rand}!`) 45 | } else { 46 | console.log(`O valor é zero!`) 47 | } 48 | 49 | // C 50 | if (rand > 0) { 51 | console.log(`O valor é positivo: ${rand}!`) 52 | } 53 | if (rand < 0) { 54 | console.log(`O valor é negativo: ${rand}!`) 55 | } 56 | if (rand === 0) { 57 | console.log(`O valor é zero!`) 58 | } 59 | 60 | // Outra forma de escrever, equivalente ao A e B... 61 | // 62 | // if (rand > 0) { 63 | // console.log(`O valor é positivo: ${rand}!`) 64 | // } else if (rand < 0) { 65 | // console.log(`O valor é negativo: ${rand}!`) 66 | // } else { 67 | // console.log(`O valor é zero!`) 68 | // } -------------------------------------------------------------------------------- /condicionais/04.js: -------------------------------------------------------------------------------- 1 | // Reescreva a próxima expressão usando 2 | // um if / else. 3 | // switch (day) { 4 | // case 0: 5 | // console.log("Segunda") 6 | // break 7 | // case 1: 8 | // console.log("Terça") 9 | // break 10 | // case 2: 11 | // console.log("Quarta") 12 | // break 13 | // case 3: 14 | // console.log("Quinta") 15 | // break 16 | // case 4: 17 | // console.log("Sexta") 18 | // break 19 | // case 5: 20 | // console.log("Sábado") 21 | // break 22 | // case 6: 23 | // console.log("Domingo") 24 | // break 25 | // default: 26 | // throw "Dia inválido!" 27 | // } 28 | if (day === 0) { 29 | console.log("Segunda") 30 | } else if (day === 1) { 31 | console.log("Terça") 32 | } else if (day === 2) { 33 | console.log("Quarta") 34 | } else if (day === 3) { 35 | console.log("Quinta") 36 | } else if (day === 4) { 37 | console.log("Sexta") 38 | } else if (day === 5) { 39 | console.log("Sábado") 40 | } else if (day === 6) { 41 | console.log("Domingo") 42 | } else { 43 | alert("Dia inválido!") 44 | } 45 | 46 | // Reescreva a próxima expressão usando 47 | // o operador ternário 48 | // let rand 49 | // if (Math.random() > 0.5) { 50 | // rand = true 51 | // } else { 52 | // rand = false 53 | // } 54 | let rand = Math.random() > 0.5 ? true : false 55 | 56 | // Reescreva a próxima expressão usando 57 | // o operador ternário 58 | // let color 59 | // if (r > g && r > b) { 60 | // color = "Vermelho" 61 | // } else if (g > b && g > r) { 62 | // color = "Verde" 63 | // } else if (b > r && b > g) { 64 | // color = "Azul" 65 | // } 66 | const r = Math.random() * 256 67 | const g = Math.random() * 256 68 | const b = Math.random() * 256 69 | let color = r > g && r > b ? "Vermelho" 70 | : g > b && g > r ? "Verde" 71 | : b > r && b > g ? "Azul" 72 | : "Cor indefinida" 73 | 74 | -------------------------------------------------------------------------------- /extra/condicionais.js: -------------------------------------------------------------------------------- 1 | // Escreva uma condicional que 2 | // verifica se dois numeros 3 | // são iguais. 4 | if (x === y) { 5 | console.log("Os números são iguais.") 6 | } else { 7 | console.log("Os números não são iguais.") 8 | } 9 | 10 | // Escreva uma condicional que 11 | // verifica se um ano é bissexto 12 | // ou não. 13 | if (year % 4 == 0 && year % 100 != 0 || 14 | year % 400 == 0) { 15 | console.log(`${year} é um ano bissexto.`) 16 | } else { 17 | console.log(`${year} não é um ano bissexto.`) 18 | } 19 | 20 | // Escreva uma condicional que 21 | // recebe duas coordenadas e 22 | // verifica se aquele ponto 23 | // esta no primeiro, segundo, 24 | // terceiro ou quarto quadrante 25 | // do plano cartesiano. 26 | if (x > 0 && y > 0) { 27 | console.log(`A coordenada (${x}, ${y}) está no primeiro quadrante.`) 28 | } else if (x < 0 && y > 0) { 29 | console.log(`A coordenada (${x}, ${y}) está no segundo quadrante.`) 30 | } else if (x < 0 && y < 0) { 31 | console.log(`A coordenada (${x}, ${y}) está no terceiro quadrante.`) 32 | } else if (x > 0 && y < 0) { 33 | console.log(`A coordenada (${x}, ${y}) está no quarto quadrante.`) 34 | } else { 35 | console.error(`Não foi possível determinar em qual quadrante está a coordenada (${x}, ${y})`) 36 | } 37 | 38 | // Escreva uma condicional que 39 | // recebe as medidas de um triangulo 40 | // e determina se ele é isosceles, 41 | // equilatero ou escaleno. 42 | if (a === b && a === c) { 43 | console.log("O triângulo é equilátero.") 44 | } else if (a !== b && b === c || b !== c && a === b) { 45 | console.log("O triângulo é isósceles.") 46 | } else { 47 | console.log("O triângulo é escaleno.") 48 | } 49 | 50 | // Escreva uma condicional que recebe 51 | // um caractere e determina se esse 52 | // caractere é uma vogal ou não. 53 | if ("aeiou".indexOf(char) !== -1) { 54 | console.log(`${char} é uma vogal.`) 55 | } else { 56 | console.log(`${char} não é uma vogal.`) 57 | } -------------------------------------------------------------------------------- /extra/funcoes.js: -------------------------------------------------------------------------------- 1 | // Escreva uma funcao 2 | // que recebe um número 3 | // decimal e o transforma 4 | // em hexadecimal. Não 5 | // use a funcao .toString(). 6 | function hex(num) { 7 | let result = "" 8 | do { 9 | let remainder = num % 16 10 | switch (remainder) { 11 | case 10: 12 | remainder = "A" 13 | break 14 | case 11: 15 | remainder = "B" 16 | break 17 | case 12: 18 | remainder = "C" 19 | break 20 | case 13: 21 | remainder = "D" 22 | break 23 | case 14: 24 | remainder = "E" 25 | break 26 | case 15: 27 | remainder = "F" 28 | break 29 | } 30 | result = remainder + result 31 | num = Math.floor(num / 16) 32 | } while (num > 0) 33 | return result 34 | } 35 | 36 | // Escreva uma funcao que 37 | // recebe uma quantidade n 38 | // e retorna os n primeiros 39 | // numeros da sequencia de 40 | // Fibonacci. 41 | function fibonacci(terms) { 42 | if (typeof terms !== "number") { 43 | throw "Por favor, forneça um número de termos para a sequência." 44 | } 45 | if (terms < 2) { 46 | throw "Por favor, forneça um número maior do que 1." 47 | } 48 | terms = Math.ceil(terms) 49 | 50 | let fib = [1, 1] 51 | for (let i = 2; i < terms; i++) { 52 | fib.push(fib[fib.length - 1] + fib[fib.length - 2]) 53 | } 54 | 55 | return fib 56 | } 57 | 58 | // Escreva uma funcao que 59 | // recebe dois numeros e retorna 60 | // o minimo multiplo comum 61 | // entre eles. 62 | function mmc(num1, num2) { 63 | let remainder, a, b 64 | a = num1 65 | b = num2 66 | 67 | do { 68 | remainder = a % b 69 | 70 | a = b 71 | b = remainder 72 | 73 | } while (remainder !== 0) 74 | 75 | return (num1 * num2) / a 76 | } 77 | 78 | // Escreva uma funcao que 79 | // recebe uma quantidade n 80 | // e printa no console 81 | // n numero de linhas do 82 | // seguinte padrao: 83 | // 84 | // 1234567654321 85 | // 12345654321 86 | // 123454321 87 | // 1234321 88 | // 12321 89 | // 121 90 | // 1 91 | function pyramid(lines) { 92 | for (let i = lines; i > 0; i--) { 93 | const spaces = " ".repeat(lines - i) 94 | let digits = "" 95 | for (let j = -i + 1; j < i; j++) { 96 | const abs_j = Math.abs(j) 97 | digits += `${Math.abs(abs_j - i)}` 98 | } 99 | console.log(spaces + digits) 100 | } 101 | } 102 | 103 | // Escreva um funcao que 104 | // recebe um numero e retorna 105 | // true se ele for primo e false 106 | // se nao. 107 | function isPrime(num) { 108 | if (typeof num !== "number") { 109 | throw "Por favor, forneça um número." 110 | } 111 | 112 | num = Math.ceil(Math.abs(num)) 113 | 114 | if (num === 0) return true 115 | if (num === 1) return false 116 | 117 | for (let i = 2; i < num; i++) { 118 | if (num % i === 0) { 119 | return false 120 | } 121 | } 122 | 123 | return true 124 | } 125 | 126 | // Escreva uma funcao que 127 | // calcula a soma de todos 128 | // os elementos em um array. 129 | function sum(arr) { 130 | let sum = 0 131 | for (const item of arr) { 132 | if (typeof item !== "number") { 133 | throw "Por favor, forneça uma lista só de números." 134 | } 135 | sum += item 136 | } 137 | return sum 138 | } 139 | 140 | // Escreva uma funcao que 141 | // recebe um array e um 142 | // elemento e determina 143 | // se o array inclui esse 144 | // elemento. Não use o metodo 145 | // .includes dos arrays. 146 | function includes(el, arr) { 147 | for (const item of arr) { 148 | if (el === item) return true 149 | } 150 | return false 151 | } 152 | 153 | // Escreva uma funcao que 154 | // recebe duas ou mais arrays 155 | // e retorna true se elas 156 | // forem exatamente iguais. 157 | function arraysAreEqual(arr1, arr2) { 158 | if (arr1 === arr2) return true 159 | if (arr1.length !== arr2.length) return false 160 | for (let i = 0; i < arr1.length; i++) { 161 | if (arr1[i] !== arr2[i]) return false 162 | } 163 | return true 164 | } 165 | 166 | // Escreva uma funcao 167 | // que recebe dois ou mais 168 | // objetos e retorna true se 169 | // eles forem exatamente iguais. 170 | function objectsAreEqual(objA, objB) { 171 | if (objA === objB) return true 172 | 173 | const aProps = Object.keys(objA) 174 | const bProps = Object.keys(objB) 175 | 176 | if (aProps.length !== bProps.length) return false 177 | 178 | for (let i = 0; i < aProps.length; i++) { 179 | const prop = aProps[i] 180 | if (objA[prop] !== objB[prop]) return false 181 | } 182 | 183 | return true 184 | } 185 | 186 | // Escreva uma funcao que 187 | // recebe duas arrays e retorna 188 | // uma terceira array com 189 | // todos os elementos da 190 | // primeira array que nao 191 | // estao presentes na segunda. 192 | function diff(arr1, arr2) { 193 | let result = [] 194 | for (const item of arr1) { 195 | if (!arr2.includes(item)) result.push(item) 196 | } 197 | for (const item of arr2) { 198 | if (!arr1.includes(item)) result.push(item) 199 | } 200 | return result 201 | } 202 | 203 | // Escreva um funcao que 204 | // recebe um objeto e retorna 205 | // um array com todas as chaves 206 | // desse objeto. Não use a funcao 207 | // Object.keys(). 208 | function keys(obj) { 209 | let arr = [] 210 | for (const key in obj) { 211 | arr.push(key) 212 | } 213 | return arr 214 | } -------------------------------------------------------------------------------- /extra/loops.js: -------------------------------------------------------------------------------- 1 | // Escreva um loop que 2 | // printa no console os dez 3 | // primeiros números naturais. 4 | for (let i = 0; i < 10; i++) { 5 | console.log(i) 6 | } 7 | 8 | // Escreva um loop que 9 | // calcula a soma dos 10 | // cem primeiros números 11 | // impares, começando pelo 1. 12 | let count = 0 13 | let sum = 0 14 | let term = 1 15 | while (count < 100) { 16 | sum += term 17 | term += 2 18 | count++ 19 | } 20 | 21 | // Escreva um loop que 22 | // printa no console o 23 | // seguinte padrao: 24 | // 1 25 | // 2 2 26 | // 3 3 3 27 | // 4 4 4 4 28 | const lines = 4 29 | for (let i = 1; i <= lines; i++) { 30 | const spaces = " ".repeat(lines - i) 31 | const digits = `${i} `.repeat(i) 32 | console.log(spaces + digits) 33 | } 34 | 35 | // Escreva um loop que calcula 36 | // a soma dos cem primeiros 37 | // numeros da serie harmonica: 38 | // 1 + 1 / 2 + 1 / 3 + ... + 1 / 100 39 | // e printa no console a expressão. 40 | let sum = 0 41 | let expression = "" 42 | for (let i = 1; i <= 100; i++) { 43 | sum += 1 / i 44 | expression = `${expression} + 1 / ${i}` 45 | } 46 | expression = `${expression.substr(3)} = ${sum}` 47 | console.log(expression) 48 | 49 | // Escreva um loop que calcula 50 | // a soma dos 10 primeiros termos 51 | // da seguinte expressão: 52 | // 1 + 11 + 111 + ... + 1111111111 53 | let sum = 0 54 | for (let i = 1; i <= 10; i++) { 55 | sum += parseInt("1".repeat(i)) 56 | } 57 | 58 | // Escreva um loop que 59 | // printa no console o 60 | // seguinte padrão: 61 | // * 62 | // *** 63 | // ***** 64 | // ******* 65 | // ********* 66 | // ******* 67 | // ***** 68 | // *** 69 | // * 70 | const lines = 4 71 | for (let i = -lines; i <= lines; i++) { 72 | const abs_i = Math.abs(i) 73 | const spaces = " ".repeat(abs_i) 74 | const asteriscs = "*".repeat(Math.abs(abs_i - lines) * 2 + 1) 75 | console.log(spaces + asteriscs) 76 | } 77 | 78 | // Escreva um loop que 79 | // printa no console o 80 | // seguinte padrão: 81 | // A 82 | // A B A 83 | // A B C B A 84 | // A B C D C B A 85 | const lines = 4 86 | for (let i = 0; i < lines; i++) { 87 | const spaces = " ".repeat(lines - i) 88 | let chars = "" 89 | for (let j = -i; j <= i; j++) { 90 | const abs_j = Math.abs(j) 91 | chars += `${String.fromCharCode(65 + Math.abs(abs_j - i))} ` 92 | } 93 | console.log(spaces + chars) 94 | } 95 | 96 | // Escreva um loop que 97 | // determina o comprimento 98 | // de uma String sem usar 99 | // a propriedade .length 100 | // da linguagem. 101 | let str = "lorem ipsum" 102 | let count = 0 103 | for (const char in str.slice("")) { 104 | count++ 105 | } 106 | 107 | // Escreva um loop que 108 | // reverte uma String. 109 | // Exemplo: Ola -> alO 110 | const str = "Beatriz" 111 | let reversed = "" 112 | for (let i = str.length - 1; i >= 0; i--) { 113 | reversed += str.charAt(i) 114 | } 115 | console.log(`${str} -> ${reversed}`) -------------------------------------------------------------------------------- /extra/objetos.js: -------------------------------------------------------------------------------- 1 | // Defina um objeto que 2 | // descreve um dos personagens 3 | // da série Harry Potter. 4 | // ref: https://pt.wikipedia.org/wiki/Lista_de_personagens_da_s%C3%A9rie_Harry_Potter 5 | const Bellatrix_Lestrange = { 6 | first_name: "Bellatrix", 7 | last_name: "Lestrange", 8 | house: "Slytherin", 9 | wand: "Twelve and three-quarter inches, walnut, dragon heartstring", 10 | occupation: "Death Eater" 11 | } 12 | 13 | // Defina um objeto que descreve 14 | // um dos feiticos da serie Harry Potter. 15 | // Cada um desses feiticos deve 16 | // conter uma propriedade cujo 17 | // valor e um numero entre -10 a 10 18 | // que determina o dano que esse 19 | // feitico causaria quando atingisse 20 | // outro personagem. 21 | // ref: http://ggryffindor.blogspot.com/p/lista-de-feiticos.html 22 | const Expelliarmus = { 23 | name: "Expelliarmus", 24 | purpose: "To remove an object (often a wand) from the recipient’s hand" 25 | } 26 | const Petrificus_Totallus = { 27 | name: "Petrificus Totalus", 28 | purpose: "To temporarily paralyse someone" 29 | } 30 | const Wingardium_Leviosa = { 31 | name: "Wingardium Leviosa", 32 | purpose: "The subject will float into the air" 33 | } 34 | 35 | // Defina um metodo .spell 36 | // no objeto do personagem que 37 | // voce criou que retorna um feitico 38 | // randomico se chamado 39 | // sem nenhum argumento, ou 40 | // retorna um determinado feitico 41 | // quando passado um argumento. 42 | Bellatrix_Lestrange.spell = function () { 43 | const spells = [Expelliarmus, Petrificus_Totallus, Wingardium_Leviosa] 44 | const random_index = Math.floor(Math.random() * spells.length) 45 | return spells[random_index] 46 | } 47 | 48 | // Defina uma nova propriedade 49 | // no objeto do personagem 50 | // que determina a quantidade 51 | // de vida que esse personagem tem. 52 | Bellatrix_Lestrange.hp = 100 53 | 54 | // Defina um metodo .damage 55 | // que recebe um feitico e 56 | // diminui a quantidade de 57 | // vida do personagem de acordo 58 | // com o dano que o feitico causa. 59 | Expelliarmus.damage = -10 60 | Petrificus_Totallus.damage = -30 61 | Wingardium_Leviosa.damage = 0 62 | Bellatrix_Lestrange.damage = function (spell) { 63 | this.hp -= spell.damage 64 | } 65 | 66 | // Escreva um funcao do 67 | // tipo `constructor` que 68 | // nos permita criar varios 69 | // objetos para diferentes 70 | // personagens da serie Harry Potter. 71 | function Character(first_name, last_name, house, wand, occupation, known_spells) { 72 | this.first_name = first_name 73 | this.last_name = last_name 74 | this.wand = wand 75 | this.occupation = occupation 76 | this.known_spells = known_spells 77 | this.hp = 100 78 | this.damage = function(spell) { 79 | this.hp -= spell.damage 80 | } 81 | this.spell = function () { 82 | const random_index = Math.floor(Math.random() * this.known_spells.length) 83 | return this.known_spells[random_index] 84 | } 85 | } 86 | 87 | // Escreva um funcao do 88 | // tipo `constructor` que 89 | // nos permite criar varios 90 | // objetos para diferentes 91 | // feiticos da serie Harry Potter. 92 | function Spell(name, purpose, damage) { 93 | this.name = name 94 | this.purpose = purpose 95 | this.damage = damage 96 | } 97 | 98 | // Escreva uma funcao quee recebe 99 | // dois personages e faz os dois 100 | // "duelarem" ate que a vida de um 101 | // deles chegue em 0. Use sua 102 | // criatividade para determinar como 103 | // essa funcao deve se comportar. 104 | function duel(character1, character2) { 105 | if (!(character1 instanceof Character) || !(character2 instanceof Character)) { 106 | throw "Por favor, forneça dois objetos do tipo `Character`" 107 | } 108 | console.log("Começar!") 109 | let players = [character1, character2] 110 | let current_player_index = Math.floor(Math.random() * 2) 111 | let next_player_index = current_player_index === 1 ? 0 : 1 112 | while (character1.hp > 0 && character2.hp > 0) { 113 | const spell = players[current_player_index].spell() 114 | players[next_player_index].damage(spell) 115 | console.log(`\n${players[current_player_index].first_name} ${players[current_player_index].last_name} ataca usando ${spell.name}!`) 116 | console.log(`${players[current_player_index].first_name} ${players[current_player_index].last_name} HP: ${players[current_player_index].hp}`) 117 | console.log(`${players[next_player_index].first_name} ${players[next_player_index].last_name} HP: ${players[next_player_index].hp}`) 118 | const aux = current_player_index 119 | current_player_index = next_player_index 120 | next_player_index = aux 121 | } 122 | console.log("E o vencedor é...") 123 | if (character1.hp < 0) { 124 | return character2 125 | } else { 126 | return character1 127 | } 128 | } 129 | 130 | // Exemplo... 131 | const expelliarmus = new Spell("Expelliarmus", "To remove an object (often a wand) from the recipient’s hand", 10) 132 | const stupefy = new Spell("Stupefy", "To stun an opponent, rendering them unconscious", 40) 133 | const petrificus_totalus = new Spell("Petrificus Totalus", "To temporarily paralyse someone", 25) 134 | const crucio = new Spell("Crucio", "To inflict excruciating pain on the recipient/victim", 20) 135 | const avada_kedavra = new Spell("Avada Kedavra", "Instant death", 100) 136 | 137 | const bellatrix_lestrange = new Character("Bellatrix", "Lestrange", "Slytherin", "Twelve and three-quarter inches, walnut, dragon heartstring", "Death Eater", [crucio, expelliarmus, stupefy, avada_kedavra]) 138 | const sirius_black = new Character("Sirius", "Black", "Gryffindor", "Unknown", "Prisoner", [expelliarmus, stupefy, petrificus_totalus]) 139 | 140 | duel(bellatrix_lestrange, sirius_black) 141 | 142 | -------------------------------------------------------------------------------- /funcoes/01.js: -------------------------------------------------------------------------------- 1 | // hello("what") -> "Hello, world!" 2 | // hello() -> "Hello, world!" 3 | function hello() { 4 | return "Hello, world!" 5 | } 6 | 7 | // show(4) -> 16 8 | // show(-4) -> 16 9 | function show(x) { 10 | console.log(`${x} ${x * x}`) 11 | return x * x 12 | console.log(`${x} ${x * x * x}`) 13 | return x * x * x 14 | } 15 | 16 | // eq3() -> 1 17 | // eq3(1, 2, 3) -> 0 18 | // eq3("1", 1, 3) -> 0 19 | // eq3("!", "a", "b") -> 0 20 | // eq3("!", "!", !) -> Uncaught SyntaxError: Unexpected token ) 21 | function eq3(a, b, c) { 22 | console.log(a, b, c) 23 | if (a === b && a === c) { 24 | return 1 25 | } else { 26 | return 0 27 | } 28 | } 29 | 30 | // Resultado: 9, 11 31 | function sum(x) { 32 | return x + 2 33 | } 34 | const x = 5 35 | console.log(`${sum(x + 2)},${sum(sum(x + 2))}`) 36 | 37 | // Resultado: 26, 12 38 | function confusion(a, b) { 39 | a = 2 * a + b 40 | return a 41 | } 42 | let x = 2 43 | let y = 5 44 | // confusion(5, 2) 45 | // x = 2 * 5 + 2 46 | // x = 12 47 | y = confusion(y, x) // 12 48 | // confusion(12, 2) 49 | // x = 2 * 12 + 2 50 | // x = 26 51 | x = confusion(y, x) // 26 52 | console.log(`${x}, ${y}`) -------------------------------------------------------------------------------- /funcoes/02.js: -------------------------------------------------------------------------------- 1 | // Escreva uma função 2 | // em Javascript que recebe 3 | // um nome, um pronome e um objeto 4 | // e retorna " foi caminhar 5 | // no parque. encontrou 6 | // . decidiu levar 7 | // pra casa." 8 | function frase(nome, pronome, objeto) { 9 | return `${nome} foi caminhar 10 | no parque. ${pronome} encontrou 11 | ${objeto}. ${nome} decidiu levar 12 | ${objeto} pra casa.` 13 | } 14 | 15 | // Escreva uma função 16 | // em Javascript que recebe 17 | // um número qualquer e retorna 18 | // a raiz quadrada dele. 19 | function sqrt(num) { 20 | if (num < 0) { 21 | throw "Não existe raiz quadrada de número negativo!" 22 | } else if (typeof num !== "number") { 23 | throw "Por favor, insira um número." 24 | } 25 | return num ** (1/2) 26 | } 27 | // ou... 28 | function sqrt(num) { 29 | return Math.sqrt(num) 30 | } 31 | 32 | // Escreva uma função em 33 | // Javascript que recebe um 34 | // número qualquer e retorna 35 | // a representação binaria dele. 36 | function binary(num) { 37 | let result = "" 38 | do { 39 | result = (num % 2) + result 40 | num = Math.floor(num / 2) 41 | } while (num > 0) 42 | return result 43 | } 44 | 45 | // binary(43) -> 46 | // 1 iteracao -> result = ""; num = 43; result = 43 % 2 + "" = "1" 47 | // 2 iteracao -> result = "1"; num = 21; result = 21 % 2 + "1" = "11" 48 | // 3 iteracao -> result = "11"; num = 10; result = 10 % 2 + "11" = "011" 49 | // 4 iteracao -> result = "011"; num = 5; result = 5 % 2 + "011" = "1011" 50 | // 5 iteracao -> result = "1011"; num = 2; result = 2 % 2 + "1011" = "01011" 51 | // 6 iteracao -> result = "01011"; num = 1; result = 1 % 2 + "01011" = "101011" 52 | // PARA 53 | // result => "101011" 54 | 55 | function binary(x) { 56 | return x.toString(2) 57 | } 58 | 59 | // Escreva uma função em Javascript 60 | // que recebe uma lista de números 61 | // e retorna o maior número da lista. 62 | function max(arr) { 63 | if (typeof arr !== "object") { 64 | throw "Por favor, forneça uma lista." 65 | } 66 | 67 | let larger = -Infinity 68 | for (const item of arr) { 69 | if (typeof item !== "number") { 70 | throw "Por favor, forneça uma lista só de nuúmeros." 71 | } 72 | if (item > larger) { 73 | larger = item 74 | } 75 | } 76 | return larger 77 | } 78 | 79 | // max([5, 6, 2, 9, 1]) -> 80 | // 1 iteracao -> item = 5; larger = -Infinity; 5 > -Infinity ? 81 | // 2 iteracao -> item = 6; larger = 5; 6 > 5 ? 82 | // 3 iteracao -> item = 2; larger = 6; 2 > 6 ? 83 | // 4 iteracao -> item = 9; larger = 6; 9 > 6 ? 84 | // 5 iteracao -> item = 1; larger = 9; 1 > 9 ? 85 | // larger = 9 86 | 87 | // ou... 88 | function max(arr) { 89 | if (typeof arr !== "object") { 90 | throw "Por favor, forneça uma lista." 91 | } 92 | 93 | let larger = arr[0] 94 | for (const item of arr) { 95 | if (typeof item !== "number") { 96 | throw "Por favor, forneça uma lista só de nuúmeros." 97 | } 98 | if (item > larger) { 99 | larger = item 100 | } 101 | } 102 | return larger 103 | } 104 | // ou.. 105 | function max(arr) { 106 | return Math.max(...arr) 107 | } 108 | // ou... 109 | function max(arr) { 110 | return Math.max.apply(null, arr) 111 | } 112 | 113 | // Escreva uma função em Javascript 114 | // que vai checar se duas ou mais strings 115 | // sao anagramas umas das outras. 116 | function sortCharactersInString(str) { 117 | return str 118 | .split("") 119 | .sort(function(a, b) { 120 | a = a.toLowerCase() 121 | b = b.toLowerCase() 122 | return a.localeCompare(b) 123 | }) 124 | .join("") 125 | } 126 | 127 | function areAnagrams(a, b) { 128 | if (a === undefined || b === undefined) { 129 | throw "Por favor, forneça pelo menos duas strings." 130 | } 131 | if (typeof a !== "string" || typeof a !== "string") { 132 | throw "Por favor, forneça uma lista só de Strings." 133 | } 134 | 135 | let first = sortCharactersInString(a) 136 | for (let i = 1; i < arguments.length; i++) { 137 | if (typeof arguments[i] !== "string") { 138 | throw "Por favor, forneça uma lista só de Strings." 139 | } 140 | if (sortCharactersInString(arguments[i]) !== first) { 141 | return false 142 | } 143 | } 144 | 145 | return true 146 | } 147 | 148 | // areAnagrams("alice", "celia", "alcei") -> 149 | // first = "aceil" 150 | // 1 iteracao -> i = 1; arguments[1] = "celia"; "aceil" !== first ? 151 | // 2 iteracao -> i = 2; arguments[2] = "alcei"; "aceil" !== first ? 152 | // PARA 153 | 154 | // Escreva uma função em Javascript 155 | // que recebe o raio de um circulo 156 | // e calcula o diametro, a circunferencia 157 | // e a area dele. 158 | function circleDimensions(r) { 159 | const diameter = r * 2 160 | const circunference = diameter * Math.PI 161 | const area = Math.PI * r * r 162 | return [ diameter, circunference, area ] // opcional 163 | } -------------------------------------------------------------------------------- /loops/01.js: -------------------------------------------------------------------------------- 1 | // Escreva um loop em Javascript 2 | // que vai calcular a soma de todos 3 | // os números entre 0 e 300. 4 | let soma = 0 5 | for (let i = 0; i <= 300; i++) { 6 | soma += i // soma = soma + i 7 | } 8 | 9 | // para maximo = 3 10 | // 1 iteracao -> soma = 0; i = 0 -> soma = 0 + 0 = 0 11 | // 2 iteracao -> soma = 0; i = 1 -> soma = 0 + 1 = 1 12 | // 3 iteracao -> soma = 1; i = 2 -> soma = 1 + 2 = 3 13 | // 4 iteracao -> soma = 3; i = 3 -> soma = 3 + 3 = 6 14 | // 5 iteracao -> soma = 6; i = 4 // PARA 15 | // FINAL -> soma = 6 16 | 17 | // Escreva um loop em Javascript 18 | // que vai calcular a seguinte soma: 19 | // 1 * 1 + 2 * 2 + 3 * 3 + ... + 400 * 400 20 | let soma = 0 21 | for (let i = 1; i <= 400; i++) { 22 | // soma += i * i 23 | // soma += Math.pow(i, 2) 24 | soma += i ** 2 25 | } 26 | 27 | // para maximo = 3 28 | // 1 iteracao -> soma = 0; i = 1 -> soma = 0 + 1 * 1 = 1 29 | // 2 iteracao -> soma = 1; i = 2 -> soma = 1 + 2 * 2 = 5 30 | // 3 iteracao -> soma = 5; i = 3 -> soma = 5 + 3 * 3 = 14 31 | // 4 iteracao -> soma = 14; i = 4 // PARA 32 | // FINAL -> soma = 14 33 | 34 | let soma = 0 35 | let x, y 36 | for (x = 1, y = 1; x <= 400, y <= 400; x++, y++) { 37 | let z = x * y 38 | soma += z 39 | } 40 | 41 | // Escreva um loop em Javascript 42 | // que vai calcular a seguinte soma: 43 | // 1 * 2 + 2 * 3 + 3 * 4 + ... + 249 * 250 44 | let soma = 0 45 | for (let i = 2; i <= 250; i++) { 46 | soma += i * (i - 1) 47 | } 48 | 49 | // para maximo = 3 50 | // 1 iteracao -> soma = 0; i = 2 -> soma = 0 + 2 * (2 - 1) = 2 51 | // 2 iteracao -> soma = 2; i = 3 -> soma = 2 + 3 * (3 - 1) = 8 52 | // 3 iteracao -> soma = 8; i = 4 -> soma = 8 + 4 * (4 - 1) = 20 53 | // 4 iteracao -> soma = 20; i = 5 -> soma = 20 + 5 * (5 - 1) = 40 54 | // 5 iteracao -> soma = 40; i = 6 // PARA 55 | // FINAL -> soma = 40 56 | 57 | for (let i = 1; i < 250; i++) { 58 | soma += i * (i + 1) 59 | } 60 | 61 | let soma = 1 62 | let multi = 1 63 | for (let i = 1; i <= 249; i++) { 64 | multi = i * (i + 1) 65 | soma = soma + multi 66 | } 67 | 68 | for (x = 1, y = 2; x <= 249, y <= 250; x++, y++) { 69 | let z = x * y 70 | soma += z 71 | } 72 | 73 | // Escreva um loop em Javascript que 74 | // vai calcular 10! (10 fatorial), o 75 | // que significa 10 * 9 * 8 * 7 ... * 1. 76 | let fatorial = 10 77 | for (let i = fatorial - 1; i > 0; i--) { 78 | fatorial *= i // fatorial = fatorial * i 79 | } 80 | 81 | let fatorial = 10 82 | let aux = 1 83 | for (let i = 1; i <= fatorial; i++) { 84 | aux *= i 85 | } 86 | 87 | // Escreva um loop em Javascript que 88 | // calcula quantos termos a soma 89 | // 1 + 2 + 3 + ... precisa para 90 | // que o resultado dela exceda um milhão. 91 | let soma = 0 92 | let i = 0 93 | while (soma <= 1000000) { 94 | i++ // i = i + 1 95 | soma += i 96 | } 97 | 98 | // Escreva um loop em Javascript que 99 | // simule o problema 3x + 1 para o número 5. 100 | // ref: https://pt.wikipedia.org/wiki/Conjectura_de_Collatz 101 | // "Esta conjectura aplica-se a qualquer 102 | // número natural não nulo, e diz-nos para, 103 | // se este número for par, o dividir 104 | // por 2 (/2), e se for impar, para 105 | // multiplicar por 3 e adicionar 1 (*3+1). 106 | // Desta forma, por exemplo, se a sequência 107 | // iniciar com o número 5 ter-se-á: 5; 16; 8; 4; 2; 1". 108 | let collatz = 5 109 | while (collatz > 1) { 110 | if (collatz % 2 === 0) { 111 | collatz = collatz / 2 112 | } else { 113 | collatz = collatz * 3 + 1 114 | } 115 | } 116 | 117 | // 1 iteracao -> collatz = 5; IMPAR collatz = 5 * 3 + 1 = 16 118 | // 2 iteracao -> collatz = 16; PAR collatz = 16 / 2 = 8 119 | // 3 iteracao -> collatz = 8; PAR collatz = 8 / 2 = 4 120 | // 4 iteracao -> collatz = 4; PAR collatz = 4 / 2 = 2 121 | // 5 iteracao -> collatz = 2; PAR collatz = 2 /2 = 1 122 | // PARA 123 | 124 | // Escreva um loop em Javascript 125 | // que gera uma lista com 100 126 | // número randomicos. 127 | let arr = [] 128 | for (let i = 0; i < 100; i++) { 129 | arr.push(Math.floor(Math.random() * 100)) 130 | } 131 | // ou... 132 | while (arr.length < 100) { 133 | arr.push(Math.floor(Math.random() * 100)) 134 | } 135 | // ou... 136 | do { 137 | arr.push(Math.floor(Math.random() * 100)) 138 | } while (arr.length < 99) 139 | 140 | // Escreva um loop em Javascript 141 | // que "lance uma moeda" a cada 142 | // nova iteração. Considere 1 = cara, 143 | // 0 = coroa. Rode esse loop 1000 vezes e 144 | // printe o numero de caras e o numero 145 | // de coroas no console. 146 | let cara = 0 147 | let coroa = 0 148 | for (let i = 0; i < 1000; i++) { 149 | let moeda = Math.floor(Math.random() * 2) 150 | if (moeda === 1) { 151 | cara++ 152 | } else { 153 | coroa++ 154 | } 155 | } 156 | // ou... 157 | while (cara + coroa < 1000) { 158 | let moeda = Math.floor(Math.random() * 2) 159 | if (moeda === 1) { 160 | cara++ 161 | } else { 162 | coroa++ 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /loops/02.js: -------------------------------------------------------------------------------- 1 | // Escreva um loop em Javascript 2 | // que gera uma matriz de zeros 5x5. 3 | // [ [0, 0, 0, 0, 0], 4 | // [0, 0, 0, 0, 0], 5 | // [0, 0, 0, 0, 0], 6 | // [0, 0, 0, 0, 0], 7 | // [0, 0, 0, 0, 0] ] 8 | let matriz = [] 9 | for (let j = 0; j < 5; j++) { 10 | let linha = [] 11 | for (let i = 0; i < 5; i++) { 12 | linha.push(0) 13 | } 14 | matriz.push(linha) 15 | } 16 | // ou... 17 | let linha = [] 18 | for (let i = 0; i < 5; i++) { 19 | linha.push(0) 20 | } 21 | let matriz = [] 22 | for (let i = 0; i < 5; i++) { 23 | matriz.push(linha) 24 | } 25 | // ou.. 26 | // nao pratico, porque? referencias. 27 | // ref: https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0 28 | let matriz = [] 29 | let linha = [] 30 | for (let i = 0; i < 5; i++) { 31 | linha.push(0) 32 | matriz.push(linha) 33 | } 34 | 35 | // Escreva um loop em Javascript 36 | // que gera uma matriz no seguinte 37 | // formato: 38 | // [ [0, 1, 2, 3, 4], 39 | // [1, 0, 1, 2, 3], 40 | // [2, 1, 0, 1, 2], 41 | // [3, 2, 1, 0, 1], 42 | // [4, 3, 2, 1, 0] ] 43 | let matriz = [] 44 | for (let j = 0; j < 5; j++) { // A 45 | let linha = [] 46 | for (let i = 0; i < 5; i++) { // B 47 | linha.push(Math.abs(i - j)) 48 | } 49 | matriz.push(linha) 50 | } 51 | 52 | // 1 iteracao A -> j = 0; matriz = [] 53 | // 1 iteracao B -> i = 0; linha = []; linha.push(0 - 0) -> linha = [0] 54 | // 2 iteracao B -> i = 1; linha = [0]; linha.push(1 - 0) -> linha = [0, 1] 55 | // 3 iteracao B -> i = 2; linha = [0, 1]; linha.push(2 - 0) -> linha = [0, 1, 2] 56 | // 4 iteracao B -> i = 3; linha = [0, 1, 2]; linha.push(3 - 0) -> linha = [0, 1, 2, 3] 57 | // 5 iteracao B -> i = 4; linha = [0, 1, 2, 3]; linha.push(4 - 0) -> linha = [0, 1, 2, 3, 4] 58 | // matriz.push([0, 1, 2, 3, 4]) -> matriz = [[0, 1, 2, 3, 4]] 59 | // 2 iteracao A -> j = 1; matriz = [[0, 1, 2, 3, 4]] 60 | // 1 iteracao B -> i = 0; linha = []; linha.push(0 - 1) -> linha = [-1] 61 | // 2 iteracao B -> i = 1; linha = [-1]; linha.push(1 - 1) -> linha = [-1, 0] 62 | // 3 iteracao B -> i = 2; linha = [-1, 0]; linha.push(2 - 1) -> linha = [-1, 0, 1] 63 | // 4 iteracao B -> i = 3; linha = [-1, 0, 1]; linha.push(3 - 1) -> linha = [-1, 0, 1, 2] 64 | // 5 iteracao B -> i = 4; linha = [-1, 0, 1, 2]; linha.push(4 - 1) -> linha = [-1, 0, 1, 2, 3] 65 | // matriz.push([-1, 0, 1, 2, 3]) -> matriz = [[0, 1, 2, 3, 4], [-1, 0, 1, 2, 3]] 66 | // ... 67 | 68 | // Escreva um loop em Javascript 69 | // que printa o seguinte padrão 70 | // no console: 71 | // ******* 72 | // ****** 73 | // ***** 74 | // **** 75 | // *** 76 | // ** 77 | // * 78 | for (let j = 0; j < 7; j++) { 79 | let asteriscos = "" 80 | for (let i = 0; i < (7 - j); i++) { 81 | asteriscos += "*" 82 | } 83 | console.log(asteriscos) 84 | } 85 | // ou... 86 | for (let j = 0; j < 7; j++) { 87 | let asteriscos = "" 88 | for (let i = j; i < 7; i++) { 89 | asteriscos += "*" 90 | } 91 | console.log(asteriscos) 92 | } 93 | // ou... 94 | let asteriscos = "********" 95 | while (asteriscos.length > 1) { 96 | asteriscos = asteriscos.substr(1, (asteriscos.length - 1)) 97 | console.log(asteriscos) 98 | } 99 | // ou... 100 | let asteriscos = ["*", "*", "*", "*", "*", "*", "*", "*"] 101 | for (let i = 7; i < 7; i++) { 102 | asteriscos = asteriscos.slice(1) 103 | console.log(asteriscos.join("")) 104 | } 105 | // ou... 106 | let asteriscos = ["*", "*", "*", "*", "*", "*", "*", "*"] 107 | for (let i = 0; i < 7; i++) { 108 | asteriscos.pop() 109 | console.log(asteriscos.join("")) 110 | } 111 | 112 | // Escreva um loop em Javascript 113 | // que printa o seguinte padrão 114 | // no console: 115 | // 1****** 116 | // 12***** 117 | // 123**** 118 | // 1234*** 119 | // 12345** 120 | // 123456* 121 | // 1234567 122 | for (let j = 1; j <= 7; j++) { 123 | let linha = "" 124 | for (let k = 1; k <= j; k++) { 125 | linha += k 126 | } 127 | for (let i = j; i < 7; i++) { 128 | linha += "*" 129 | } 130 | console.log(linha) 131 | } 132 | // ou... 133 | let digitos = "" 134 | for (let i = 1; i <= 7; i++) { 135 | digitos += i 136 | let numero_com_asteriscos = digitos 137 | for (let j = 7; j > i; j--) { 138 | numero_com_asteriscos += "*" 139 | } 140 | console.log(numero_com_asteriscos) 141 | } -------------------------------------------------------------------------------- /objetos/01.js: -------------------------------------------------------------------------------- 1 | // 1. 2 | // Defina um objeto de 3 | // Javascript que descreva 4 | // um dos pokemons da lista 5 | // de pokemons do Wikipedia. 6 | // ref: https://pt.wikipedia.org/wiki/Lista_de_Pok%C3%A9mon 7 | const pokemon = { 8 | numero_nacional: 143, 9 | nome: "Snorlax", 10 | nome_japones: "Kabigon", 11 | numero_johnto: 230, 12 | evolui_de: "Munchlax", 13 | janiarli_tem: true 14 | } 15 | 16 | // 2. 17 | // Printe no console a seguinte 18 | // frase: "Hello, my name is < >. 19 | // And my name in Japanese is < >." 20 | pokemon.diga_ola = function () { 21 | console.log(`Hello, my name is ${this.nome}. And my name in Japanese is ${this.nome_japones}.`) 22 | } 23 | 24 | // 3. 25 | // Adicione uma nova propriedade ao 26 | // seu pokemon chamada `can_fly` 27 | // (ou algo do tipo) e defina 28 | // ela como `true` ou `false`. 29 | pokemon.can_fly = false 30 | 31 | // 4. 32 | // Adicione um método ao seu pokemon 33 | // chamado `fly` que retorna "Sorry, 34 | // I can't fly" ou "Flyyyyiinnngggg!". 35 | pokemon.fly = function () { 36 | if (this.can_fly) { 37 | return "Flyyyyiinnngggg!" 38 | } else { 39 | return "Sorry, I can't fly" 40 | } 41 | } 42 | 43 | // 5. 44 | // Adicione um método chamado 45 | // `do_something` ao seu pokemon 46 | // que retorna randomicamente uma 47 | // das Strings "FIGHT", "BAG" ou "RUN". 48 | pokemon.do_something = function () { 49 | let acoes = ["FIGHT", "BAG", "RUN"] 50 | return acoes[Math.floor(Math.random() * acoes.length)] 51 | } 52 | // ou... 53 | pokemon.do_something = function () { 54 | const rand = Math.floor(Math.random() * 3) 55 | if (rand === 0) { 56 | return "FIGHT" 57 | } else if (rand === 1) { 58 | return "BAG" 59 | } else { 60 | return "RUN" 61 | } 62 | } 63 | 64 | // 6. 65 | // Adicione um método chamado 66 | // `ask` ao seu pokemon que printa 67 | // no console "What will do?" e 68 | // retorna o resultado do metodo 69 | // `do_something`. 70 | pokemon.ask = function () { 71 | console.log(`What will ${this.nome} do?`) 72 | return this.do_something() 73 | } 74 | 75 | // 7. 76 | // Printe todas as propriedades 77 | // do seu pokemon no console. 78 | for (const prop in pokemon) { 79 | console.log(prop) 80 | } 81 | 82 | // 8. 83 | // Printe todas as propriedades 84 | // e seus respectivos valores no 85 | // console no seguinte formato: 86 | // : 87 | for (const prop in pokemon) { 88 | console.log(`${prop}: ${pokemon[prop]}`) 89 | } 90 | 91 | // 9. 92 | // Crie uma funcao construtora 93 | // de um pokemon generico. 94 | // function (nome, nome_japones) {} 95 | function Pokemon(nome, nome_japones, pode_voar) { 96 | this.nome = nome 97 | this.nome_japones = nome_japones 98 | this.pode_voar = pode_voar 99 | this.diga_ola = function () { 100 | console.log(`Hello, my name is ${this.nome}. And my name in Japanese is ${this.nome_japones}.`) 101 | } 102 | this.voe = function () { 103 | if (this.pode_voar) { 104 | return "É nóis que voa bruxão!" 105 | } else { 106 | return "I believe I can fly, but I can't..." 107 | } 108 | } 109 | this.manda_ver = function () { 110 | let acoes = [ 111 | "Desce a porrada", 112 | "Deu ruim", 113 | "Ash, vambora daqui" 114 | ] 115 | return acoes[Math.floor(Math.random() * acoes.length)] 116 | } 117 | this.pergunte = function () { 118 | console.log(`O que ${this.nome} vai fazer?`) 119 | return this.manda_ver() 120 | } 121 | } 122 | 123 | 124 | --------------------------------------------------------------------------------