├── .github
└── workflows
│ └── master.yml
├── .gitignore
├── README.md
├── package.json
├── src
├── desafio1ao6.js
├── desafio7.js
├── desafio8.js
└── desafio9.js
└── tests
├── biggerNumber.test.js
├── formatPhoneNumber.test.js
├── getArrayNoIntervalo.test.js
├── ignoreFirstAndLastElement.test.js
├── invertElementsArray.test.js
├── invertString.test.js
├── noDuplicates.test.js
├── printElements.test.js
└── taxesCalcul.test.js
/.github/workflows/master.yml:
--------------------------------------------------------------------------------
1 | name: Continuos Integration
2 |
3 | on:
4 | pull_request:
5 | types: [opened, synchronize]
6 |
7 | jobs:
8 | continuos-integration:
9 | runs-on: ubuntu-latest
10 | name: Evaluator
11 | steps:
12 | - name: Project repository
13 | uses: actions/checkout@v3
14 | - name: Setup NodeJS
15 | uses: actions/setup-node@v2
16 | with:
17 | node-version: 16.x
18 | - name: Run Tests
19 | run: |
20 | npm install
21 | npm run test
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | node_modules
2 | ioc
3 | package-lock.json
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Boas-vindas ao repositório do Desafio!
2 |
3 | # Orientações
4 |
5 |
6 | ‼ Antes de começar a desenvolver
7 |
8 | 1. Clone o repositório
9 |
10 | * Use o comando: `https://github.com/UnifelDesenvolvimentoWeb/vanillaChallengesJS.git`
11 |
12 | * Entre na pasta do repositório que você acabou de clonar:
13 |
14 | * `cd vanillaChallengesJS`
15 |
16 | 2. Instale as dependências
17 |
18 | * Para isso, use o seguinte comando: `npm install`
19 |
20 | 3. Crie uma branch a partir da branch `master`
21 |
22 | * Verifique se você está na branch `master`
23 | * Exemplo: `git branch`
24 | * Se não estiver, mude para a branch `master`
25 | * Exemplo: `git checkout master`
26 | * Agora, crie uma branch para qual você vai submeter os `commits` do seu projeto:
27 | * Você deve criar uma branch no seguinte formato: `nome-de-usuario-nome-do-projeto`
28 | * Exemplo: `git checkout -b arthur-alves-vanillaChallenges`
29 |
30 | 4. Adicione as mudanças ao _stage_ do Git e faça um `commit`
31 | * Verifique que as mudanças ainda não estão no _stage_
32 | * Exemplo: `git status` (os arquivos no diretório `src` devem aparecer em vermelho)
33 |
34 | * Adicione o novo arquivo ao _stage_ do Git
35 | * Exemplo: `git add .` (adicionando todas as mudanças - _que estavam em vermelho_ - ao stage do Git)
36 | * `git status` (deve aparecer listado os arquivos do diretório `src` em verde)
37 |
38 | * Faça o `commit` inicial
39 | * Exemplo: `git commit -m 'iniciando o projeto.'` (fazendo o primeiro commit)
40 | * `git status` (deve aparecer uma mensagem tipo _nothing to commit_ )
41 |
42 | 5. Adicione a sua branch com o novo `commit` ao repositório remoto
43 |
44 | * Usando o exemplo anterior: `git push -u origin arthur-alves-vanillaChallenges`
45 |
46 | 6. Crie um novo `Pull Request` _(PR)_
47 | * Vá até a página de _Pull Requests_ do [repositório no GitHub](https://github.com/UnifelDesenvolvimentoWeb/VanillaChallengesJS/pulls)
48 | * Clique no botão verde _"New pull request"_
49 | * Clique na caixa de seleção _"Compare"_ e escolha a sua branch **com atenção**
50 | * Coloque um título para o seu _Pull Request_
51 | * Exemplo: _"Cria função x"_
52 | * Clique no botão verde _"Create pull request"_
53 | * Adicione uma descrição para o _Pull Request_ e clique no botão verde _"Create pull request"_
54 | * **Não se preocupe em preencher mais nada por enquanto!**
55 | * Volte até a [página de _Pull Requests_ do repositório](https://github.com/UnifelDesenvolvimentoWeb/VanillaChallengesJS/pulls) e confira que o seu _Pull Request_ está criado.
56 |
57 |
58 |
59 |
60 | 🛠 Testes
61 | Todos os requisitos do projeto serão testados automaticamente por meio do Jest.
62 |
63 | Para rodar o avaliador automático localmente no seu projeto, execute um dos comandos abaixo:
64 |
65 | Para executar todos os testes utilize:
66 | ```bash
67 | npm test
68 | ```
69 |
70 | ***ou***
71 |
72 | Para executar um arquivo de teste específico, utilize `npm test nomeDoArquivoDeTeste`:
73 |
74 | ```bash
75 | npm test taxesCalcul
76 | ```
77 |
78 |
79 |
80 |
81 | 🔗 Links auxiliares para o desenvolvimento
82 | do projeto
83 |
84 | - [JavaScript.com](http://javascript.com/)
85 |
86 | - [W3Schools](https://www.w3schools.com/js/default.asp)
87 |
88 | - [MDN](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript)
89 |
90 | - [StackOverflow](https://pt.stackoverflow.com/questions/tagged/javascript)
91 |
92 |
93 |
94 | ## 1 - Implemente a função printElements
95 |
96 |
97 |
98 | Implemente a função printElements
escreva um código que imprima todos os elementos de um array.
99 |
100 |
101 | A função `printElements` recebe um arrray por parâmetro e imprime um por um dos elementos do aray:
102 |
103 |
104 |
105 | ## 2 - Crie uma função que acha o maior número
106 |
107 |
108 |
109 | Implemente a função biggerNumber
que retorna o maior númeo dentro de um array
110 |
111 |
112 |
113 | A função `biggerNumber` recebe um array por parâmetro.
114 |
115 | **O que será testado:**
116 | Exemplo
117 |
118 | - Retorna o valor 20 quando a função é chamada com o parâmetro [1, 6, 8, 5, 19, 20, 10];
119 |
120 | - Retorna o valor 5 quando a função é chamada com o parâmetro [1, 5, 3, 2];
121 |
122 | - Retorna o valor 10 quando a função é chamada com o parâmetro [5, 8, 4, 10];
123 |
124 |
125 |
126 |
127 | ## 3 - Crie a função ignoreFirstAndLastElement
128 |
129 |
130 |
131 | Implemente a função ignoreFirstAndLastElement
e escreva um código que imprima todos os elementos de um array, exceto o primeiro e o último
132 |
133 |
134 | A função `ignoreFirstAndLastElement` recebe um array como parâmetro e deve imprimir todos os elementos menos o primeiro e o ultimo.
135 |
136 | Se o array tiver um tamanho menor que 3 deve imprimir a seguinte mensagem `'Tamanho do array inválido'`
137 |
138 | Exemplo: se a função receber o array `[1, 5, 10, 12]`, o retorno deverá ser `[5, 10]`.
139 |
140 | **O que será testado:**
141 |
142 | - Retorne o valor `['JavaScript']` se a função receber `['HTML', 'JavaScript', 'CSS']`;
143 |
144 | - Retorne o valor `[10, 5, 20]` se a função receber `[8, 10, 5, 20, 6]` ;
145 |
146 | - Retorne o valor `'Tamanho do array inválido'` se a função receber `[4, 7]`.
147 |
148 |
149 |
150 |
151 |
152 | ## 4 - Crie uma função que inverte a ordem de um array
153 |
154 |
155 |
156 | Escreva um código que inverta a ordem dos elementos de um array.
157 | Implemente a função invertElementsArray
que recebe um array e retorna esse array invertido
158 |
159 |
160 |
161 | Exemplo:
162 |
163 | - Caso o parâmetro passado para a função `invertElementsArray` seja o array `[8, 4, 60, 15]`, a função deverá retornar `[15, 60, 4, 8]`.
164 |
165 | **O que será testado:**
166 |
167 | - Retorne `[10, 7, 23]` quando o parâmetro passado na funcão concatName seja `[23, 7, 10]`;
168 |
169 | - Retorne `['uva', 'banana', 'maça']` quando o parâmetro passado na funcão concatName seja `['maça', 'banana', 'uva']`;
170 |
171 |
172 |
173 | ## 5 - Crie uma função que inverte uma string
174 |
175 |
176 |
177 | Implemente a função invertString
que inverte uma string
178 |
179 |
180 |
181 | A função `invertString` recebe uma string por parâmetro e retorna essa string invertida
182 |
183 | Exemplo:
184 |
185 | **O que será testado:**
186 |
187 | - Retorne `etrevni` quando a string passada por parâ for `inverte`;
188 |
189 | - Retorne `olleh` quando a string passada por parâ for `hello`;
190 |
191 |
192 |
193 |
194 | ## 6 - Crie uma função que retira os elementos duplicados
195 |
196 |
197 |
198 | Implemente a função noDuplicates
e escreva um código que receba um array de números por parâmetro e retorne o array com os elementos duplicados removidos.
199 |
200 |
201 |
202 | Por exemplo:
203 |
204 | - Caso o parâmetro seja um array com valores `[9, 1, 2, 3, 9, 2, 7]`, a função deverá retornar `[9, 1, 2, 3, 7]`
205 |
206 | **O que será testado:**
207 |
208 | - Retorne `[9, 2, 3, 1]` quando o parâmetro passado na função noDuplicates seja `[9, 1, 2, 3, 9, 1, 3]`;
209 |
210 | - Retorne `[0, 4, 9, 1]` quando o parâmetro passado na função noDuplicates seja `[0, 4, 4, 4, 9, 1]`;
211 |
212 | - Retorne `[0]` quando o parâmetro passado na função noDuplicates seja `[0, 0, 0]`.
213 |
214 |
215 |
216 |
217 |
218 | ## 7 - Crie uma função que calcula o salário liquido a ser receido
219 |
220 |
221 |
222 | Implemente a função taxesCalcul
que recebe por parâmetro o valor bruto (do tipo number) do salário e calcula o valor líquido.
223 |
224 |
225 | Utilize if...else para escrever um código que, dado um salário bruto, calcule o salário líquido a ser recebido.
226 | Uma pessoa que trabalha de carteira assinada no Brasil tem descontados de seu salário bruto o INSS (Instituto Nacional do Seguro Social) e o IR (Imposto de Renda).
227 |
228 | A notação para um salário de R$1.500,10, por exemplo, deve ser 1500.10.
229 |
230 | Para as faixas de impostos, use as seguintes referências:
231 |
232 | INSS
233 | Salário bruto até R$ 1.556,94: alíquota de 8%;
234 | Salário bruto de R$ 1.556,95 a R$ 2.594,92: alíquota de 9%;
235 | Salário bruto de R$ 2.594,93 a R$ 5.189,82: alíquota de 11%;
236 | Salário bruto acima de R$ 5.189,82: alíquota máxima de R$ 570,88.
237 | IR
238 | Até R$ 1.903,98: isento de imposto de renda;
239 | De R$ 1.903,99 a 2.826,65: alíquota de 7,5% e parcela de R$ 142,80 a deduzir do imposto;
240 | De R$ 2.826,66 a R$ 3.751,05: alíquota de 15% e parcela de R$ 354,80 a deduzir do imposto;
241 | De R$ 3.751,06 a R$ 4.664,68: alíquota de 22,5% e parcela de R$ 636,13 a deduzir do imposto;
242 | Acima de R$ 4.664,68: alíquota de 27,5% e parcela de R$ 869,36 a deduzir do imposto.
243 | O cálculo deve ser o demonstrado a seguir
244 | O salário bruto está entre R$ 2.594,93 e R$ 5.189,82, então sua alíquota para o INSS é de 11%. O INSS será 11% de R$ 3.000, ou seja, R$ 330,00.
245 |
246 | Para descobrir o salário-base, subtraia do salário bruto a alíquota do INSS: R$ 3.000,00 - R$ 330,00 = R$ 2.670,00.
247 |
248 | Para calcular o valor do IR, considera-se um salário-base (já deduzido o INSS) entre R$ 1.903,99 e 2.826,65, em que a alíquota é de 7.5%, com parcela de R$ 142,80 a deduzir do imposto. Assim, tem-se:
249 |
250 | R$ 2.670,00 - salário com INSS já deduzido;
251 | 7.5% - alíquota de imposto de renda, que representa um desconto de R$ 200,25;
252 | R$ 142,80 - parcela a ser deduzida do imposto de renda.
253 | Para obter o valor do imposto de renda, calcula-se: R$ 200,25 (que representa 7,5% de R$ 2.670,00) - R$ 142,80 (dedução do imposto de renda) = R$ 57,45.
254 |
255 | Para obter o salário líquido, calcula-se: R$ 2.670,00 - R$ 57,45 (salário-base - valor IR) = R$ 2.612,55.
256 |
257 | Resultado: Salário: R$ 2612.55.
258 |
259 | Exemplo:
260 |
261 | **O que será testado:**
262 |
263 | - A função recebe um valor do tipo number por parâmetro
264 |
265 | - Retorna `'Salário: R$ 2612.55.'` caso o parâmeto passado seja 3000;
266 |
267 | - Retorna `'Salário: R$ 1820'` caso o parâmeto passado seja 2000;
268 |
269 | - Retorna `'Salário: R$ 3532.1.'` caso o parâmeto passado seja 4200;
270 |
271 |
272 |
273 |
274 | ## 8 - Crie uma função de número de telefone
275 |
276 |
277 |
278 | Implemente a função formatPhoneNumber
que recebe um array com 11 números e retorna um número de telefone, respeitando parênteses, traços e espaços.
279 |
280 |
281 |
282 | Exemplo: caso o parâmetro da função seja `[1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1]`, a função `formatPhoneNumber` deverá retornar `(12) 34567-8901`.
283 |
284 | - Retorne a frase `'Array com tamanho incorreto.'` se a função receber um array com tamanho diferente de 11;
285 |
286 | - Retorne a string `'não é possível gerar um número de telefone com esses valores'` caso algum dos números do array seja **menor** que 0, **maior** que 9 ou se repita 3 vezes ou mais.
287 |
288 |
289 | **O que será testado:**
290 |
291 | - Retorne a string 'Array com tamanho incorreto.' caso o array tenha o tamanho diferente de 11;
292 |
293 | - Retorne a string "não é possível gerar um número de telefone com esses valores" caso algum dos números do array seja menor que 0;
294 |
295 | - Retorne a string "não é possível gerar um número de telefone com esses valores" caso algum número do array seja maior que 9;
296 |
297 | - Retorne a string "não é possível gerar um número de telefone com esses valores" caso algum número do array se repetir 3 vezes ou mais;
298 |
299 | - Retorne um número de telefone, respeitando parênteses, traços e espaços caso os números do array estejam de acordo com as especificações.
300 |
301 |
302 |
303 |
304 | ## 9 - Crie uma função que retorna o intevalo dentro de um array
305 |
306 |
307 |
308 | Implemente a função getArrayNoIntervalo
que recebe um array e retorna um objeto com duas key, uma delas é arrayNoIntervalo que deve conter um array com o intervalo encontrado e a outa é o contador que deve conter quantos números contem nesse intervalo
309 |
310 |
311 | A função recebe 3 parâmetos, o primeiro é um `array` de números, o segundo é um número que representa o `inicio` do intervalo selecionado, o terceiro representa o `fim` do intervalo selecionado
312 |
313 | Exemplo: caso o parâmetro da função seja `[1, 2, 3, 4, 5, 1], 2, 4`, a função `getArrayNoIntervalo` deverá retornar `{ arrayNoIntervalo: [2, 3, 4], contador: 3 };`.
314 |
315 | **O que será testado:**
316 |
317 | - Retorne o objeto `{ arrayNoIntervalo: [2, 3, 4], contador: 3 };` se a essa função for chamada com esses parâmetros `getArrayNoIntervalo([1, 2, 3, 4, 5, 1], 2, 4)`;
318 |
319 | - Retorne o objeto `{ arrayNoIntervalo: [20, 63, 80], contador: 3 };` se a essa função for chamada com esses parâmetros `getArrayNoIntervalo([20, 14, 5, 6, 9, 63, 80, 120], 20, 80)`;
320 |
321 | - Retorne o objeto `{ arrayNoIntervalo: [15, 21, 30], contador: 3 };` se a essa função for chamada com esses parâmetros `getArrayNoIntervalo([15, 4, 6, 9, 21, 30, 7], 15, 30)`;
322 |
323 |
324 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "devDependencies": {
3 | "jest": "26.1.0"
4 | },
5 | "scripts": {
6 | "test": "jest"
7 | },
8 | "jest": {
9 | "rootDir": "./tests/"
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/desafio1ao6.js:
--------------------------------------------------------------------------------
1 | const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
2 |
3 | // Desafio 1
4 | // Escreva um código que imprima um por um de todos os elementos de um array.
5 | function printElements(array) {
6 |
7 | }
8 |
9 | // Desafio 2
10 | // Escreva um código que encontre o maior elemento de um array.
11 | function biggerNumber(array) {
12 |
13 | }
14 |
15 | // Desafio 3
16 | // Escreva um código que imprima todos os elementos de um array, exceto o primeiro e o último.
17 | // Caso o array tenha um tamanho menor que 3 imprima a mensagem: 'Tamanho do array inválido'
18 | function ignoreFirstAndLastElement(array) {
19 |
20 | }
21 |
22 | // Desafio 4
23 | // Escreva um código que inverta a ordem dos elementos de um array.
24 | function invertElementsArray(array) {
25 |
26 | }
27 |
28 | // Desafio 5
29 | // Escreva um código que recebe uma string por parâmetro e imprima a sua versão invertida.
30 | function invertString(string) {
31 |
32 | }
33 |
34 | // Desafio 6
35 | // Escreva um código que receba um array de números por parâmetro e retorne
36 | // o array com os elementos duplicados removidos.
37 | function noDuplicates(array) {
38 |
39 | }
40 |
41 | module.exports = {
42 | biggerNumber,
43 | printElements,
44 | ignoreFirstAndLastElement,
45 | invertElementsArray,
46 | invertString,
47 | noDuplicates
48 | }
49 |
--------------------------------------------------------------------------------
/src/desafio7.js:
--------------------------------------------------------------------------------
1 | // Desafio 7
2 | function taxesCalcul(grossSalary) {
3 |
4 | }
5 |
6 | module.exports = {
7 | taxesCalcul
8 | }
--------------------------------------------------------------------------------
/src/desafio8.js:
--------------------------------------------------------------------------------
1 | // Desafio 8
2 | function formatPhoneNumber(telNumber) {
3 |
4 | }
5 |
6 | module.exports = {
7 | formatPhoneNumber
8 | }
--------------------------------------------------------------------------------
/src/desafio9.js:
--------------------------------------------------------------------------------
1 | // Desafio 9
2 | function getArrayNoIntervalo(array, inicio, fim) {
3 |
4 | }
5 |
6 | module.exports = {
7 | getArrayNoIntervalo
8 | }
9 |
10 |
--------------------------------------------------------------------------------
/tests/biggerNumber.test.js:
--------------------------------------------------------------------------------
1 | const { biggerNumber } = require('../src/desafio1ao6');
2 |
3 | describe('2 - biggerNumber', () => {
4 | // Returns the biggest number in an array of positive integers
5 | it('should return the biggest number in an array of positive integers', () => {
6 | const array = [1, 2, 3, 4, 5];
7 | const result = biggerNumber(array);
8 | expect(result).toBe(5);
9 | });
10 | // Returns the biggest number in an array of negative integers
11 | it('should return the biggest number in an array of negative integers', () => {
12 | const array = [-1, -2, -3, -4, -5];
13 | const result = biggerNumber(array);
14 | expect(result).toBe(-1);
15 | });
16 | // Returns the biggest number in an array of mixed positive and negative integers
17 | it('should return the biggest number in an array of mixed positive and negative integers', () => {
18 | const array = [-1, 2, -3, 4, -5];
19 | const result = biggerNumber(array);
20 | expect(result).toBe(4);
21 | });
22 | // Returns undefined when called with an empty array
23 | it('should return undefined when called with an empty array', () => {
24 | const array = [];
25 | const result = biggerNumber(array);
26 | expect(result).toBeUndefined();
27 | });
28 | });
29 |
--------------------------------------------------------------------------------
/tests/formatPhoneNumber.test.js:
--------------------------------------------------------------------------------
1 | const { formatPhoneNumber } = require('../src/desafio8')
2 |
3 | describe('formatPhoneNumber', () => {
4 | // Returns an error message when given an array of incorrect length.
5 | it('should return an error message when given an array of incorrect length', () => {
6 | const telNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9];
7 | const result = formatPhoneNumber(telNumber);
8 | expect(result).toBe('Array com tamanho incorreto.');
9 | });
10 | // Returns an error message when given an empty array.
11 | it('should return an error message when given an empty array', () => {
12 | const telNumber = [];
13 | const result = formatPhoneNumber(telNumber);
14 | expect(result).toBe('Array com tamanho incorreto.');
15 | });
16 |
17 | // Returns an error message when given an array with less than 11 digits.
18 | it('should return an error message when given an array with less than 11 digits', () => {
19 | const telNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9];
20 | const result = formatPhoneNumber(telNumber);
21 | expect(result).toBe('Array com tamanho incorreto.');
22 | });
23 |
24 | // Returns an error message when given an array with more than 11 digits.
25 | it('should return an error message when given an array with more than 11 digits', () => {
26 | const telNumber = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2];
27 | const result = formatPhoneNumber(telNumber);
28 | expect(result).toBe('Array com tamanho incorreto.');
29 | });
30 |
31 | it('Return a string "Array com tamanho incorreto." if the array has a size other than 11', () => {
32 | expect(formatPhoneNumber([0, 1, 6])).toBe('Array com tamanho incorreto.');
33 | expect(formatPhoneNumber([])).toBe('Array com tamanho incorreto.');
34 | expect(formatPhoneNumber([9, 2, 3, 0, 5, -6, 7, 8, -7, 0, 1, 10])).toBe('Array com tamanho incorreto.');
35 | });
36 |
37 | it('Return a string "não é possível gerar um número de telefone com esses valores" if any of the numbers in the array is less than 0', () => {
38 | expect(formatPhoneNumber([9, 2, 3, 0, 5, -6, 7, 8, -7, 0, 1])).toBe('não é possível gerar um número de telefone com esses valores');
39 | expect(formatPhoneNumber([3, -2, 1, 9, -5, 0, 7, 4, 0, 6, 1])).toBe('não é possível gerar um número de telefone com esses valores');
40 | expect(formatPhoneNumber([1, 2, -3, 4, 0, 6, 7, 8, 9, 9, 0])).toBe('não é possível gerar um número de telefone com esses valores');
41 | expect(formatPhoneNumber([-1, 2, 4, -4, 5, 6, 9, -8, 7, 3, 3])).toBe('não é possível gerar um número de telefone com esses valores');
42 | });
43 |
44 | it('Return a string "não é possível gerar um número de telefone com esses valores" if any number in the array is greater than 9', () => {
45 | expect(formatPhoneNumber([0, 21, 3, 4, 14, 2, 7, 8, 19, 9, 4])).toBe('não é possível gerar um número de telefone com esses valores');
46 | expect(formatPhoneNumber([1, 2, 18, 0, 5, 3, 17, 8, 9, 1, 8])).toBe('não é possível gerar um número de telefone com esses valores');
47 | expect(formatPhoneNumber([1, 2, 12, 4, 15, 5, 2, 8, 9, 10, 11])).toBe('não é possível gerar um número de telefone com esses valores');
48 | expect(formatPhoneNumber([0, 2, 3, 14, 5, 7, 71, 1, 9, 0, 7])).toBe('não é possível gerar um número de telefone com esses valores');
49 | });
50 |
51 | it('Return a string "não é possível gerar um número de telefone com esses valores" if any number in the array is repeated 3 times or more', () => {
52 | expect(formatPhoneNumber([0, 2, 3, 4, 4, 2, 7, 8, 9, 9, 4])).toBe('não é possível gerar um número de telefone com esses valores');
53 | expect(formatPhoneNumber([1, 2, 8, 0, 5, 3, 7, 8, 9, 1, 8])).toBe('não é possível gerar um número de telefone com esses valores');
54 | expect(formatPhoneNumber([1, 2, 2, 4, 5, 5, 2, 8, 9, 0, 1])).toBe('não é possível gerar um número de telefone com esses valores');
55 | expect(formatPhoneNumber([0, 2, 3, 4, 5, 7, 7, 8, 9, 0, 7])).toBe('não é possível gerar um número de telefone com esses valores');
56 | });
57 |
58 | it('Return a numbe of phone number, respecting parentheses, dashes and spaces if the numbers in the matrix comply with the restrictions', () => {
59 | expect(formatPhoneNumber([1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1])).toBe('(12) 34567-8901');
60 | expect(formatPhoneNumber([5, 2, 8, 1, 5, 3, 7, 2, 8, 9, 0])).toBe('(52) 81537-2890');
61 | expect(formatPhoneNumber([0, 2, 4, 3, 5, 5, 6, 8, 9, 2, 1])).toBe('(02) 43556-8921');
62 | expect(formatPhoneNumber([0, 2, 3, 4, 5, 8, 7, 9, 1, 0, 7])).toBe('(02) 34587-9107');
63 | });
64 | });
65 |
--------------------------------------------------------------------------------
/tests/getArrayNoIntervalo.test.js:
--------------------------------------------------------------------------------
1 | const { getArrayNoIntervalo } = require('../src/desafio9')
2 |
3 | describe('9 - getArrayNoIntervalo', () => {
4 |
5 | // Returns an object with an array and a counter when given an array and two numbers.
6 | it('should return an object with an array and a counter when given an array and two numbers', () => {
7 | const array = [1, 2, 3, 4, 5];
8 | const inicio = 2;
9 | const fim = 4;
10 |
11 | const result = getArrayNoIntervalo(array, inicio, fim);
12 |
13 | expect(result).toEqual({
14 | arrayNoIntervalo: [2, 3, 4],
15 | contador: 3
16 | });
17 | });
18 |
19 | // Returns an object with an array and a counter when given an array and two numbers.
20 | it('should return an object with an array and a counter when given an array and two numbers', () => {
21 | const array = [4, 6, 80, 100];
22 | const inicio = 6;
23 | const fim = 100;
24 |
25 | const result = getArrayNoIntervalo(array, inicio, fim);
26 |
27 | expect(result).toEqual({
28 | arrayNoIntervalo: [6, 80, 100],
29 | contador: 3
30 | });
31 | });
32 |
33 |
34 | // Returns an object with an array and a counter when given an array and two numbers.
35 | it('should return an object with an array and a counter when given an array and two numbers', () => {
36 | const array = [20, 18, 9, 15, 6, 80, 100];
37 | const inicio = 20;
38 | const fim = 80;
39 |
40 | const result = getArrayNoIntervalo(array, inicio, fim);
41 |
42 | expect(result).toEqual({
43 | arrayNoIntervalo: [20, 80],
44 | contador: 2
45 | });
46 | });
47 |
48 | // Returns an empty array and a counter of 0 when given an empty array and two numbers.
49 | it('should return an empty array and a counter of 0 when given an empty array and two numbers', () => {
50 | const array = [];
51 | const inicio = 2;
52 | const fim = 4;
53 |
54 | const result = getArrayNoIntervalo(array, inicio, fim);
55 |
56 | expect(result).toEqual({
57 | arrayNoIntervalo: [],
58 | contador: 0
59 | });
60 | });
61 |
62 | // Returns an empty array and a counter of 0 when given an array and two numbers that do not match any element in the array.
63 | it('should return an empty array and a counter of 0 when given an array and two numbers that do not match any element in the array', () => {
64 | const array = [1, 2, 3, 4, 5];
65 | const inicio = 6;
66 | const fim = 8;
67 |
68 | const result = getArrayNoIntervalo(array, inicio, fim);
69 |
70 | expect(result).toEqual({
71 | arrayNoIntervalo: [],
72 | contador: 0
73 | });
74 | });
75 |
76 | // Returns an empty array and a counter of 0 when given an array and two numbers in the wrong order.
77 | it('should return an empty array and a counter of 0 when given an array and two numbers in the wrong order', () => {
78 | const array = [1, 2, 3, 4, 5];
79 | const inicio = 4;
80 | const fim = 2;
81 |
82 | const result = getArrayNoIntervalo(array, inicio, fim);
83 |
84 | expect(result).toEqual({
85 | arrayNoIntervalo: [],
86 | contador: 0
87 | });
88 | });
89 |
90 | // Returns an empty array and a counter of 0 when given an array and two NaN values.
91 | it('should return an empty array and a counter of 0 when given an array and two NaN values', () => {
92 | const array = [1, 2, 3, 4, 5];
93 | const inicio = NaN;
94 | const fim = NaN;
95 |
96 | const result = getArrayNoIntervalo(array, inicio, fim);
97 |
98 | expect(result).toEqual({
99 | arrayNoIntervalo: [],
100 | contador: 0
101 | });
102 | });
103 | });
104 |
--------------------------------------------------------------------------------
/tests/ignoreFirstAndLastElement.test.js:
--------------------------------------------------------------------------------
1 | const { ignoreFirstAndLastElement } = require('../src/desafio1ao6')
2 |
3 | describe('3 - ignoreFirstAndLastElement', () => {
4 |
5 | // Function receives an array with length >= 3, and logs all elements except the first and last ones
6 | it('should log all elements except the first and last ones when array length is greater than or equal to 3', () => {
7 | const array = [1, 2, 3, 4, 5];
8 | const consoleSpy = jest.spyOn(console, 'log');
9 |
10 | ignoreFirstAndLastElement(array);
11 |
12 | expect(consoleSpy).toHaveBeenCalledTimes(3);
13 | expect(consoleSpy).toHaveBeenCalledWith(2);
14 | expect(consoleSpy).toHaveBeenCalledWith(3);
15 | expect(consoleSpy).toHaveBeenCalledWith(4);
16 |
17 | consoleSpy.mockRestore();
18 | });
19 |
20 | // Function receives an array with length == 3, and logs the only element in the middle
21 | it('should log the only element in the middle when array length is equal to 3', () => {
22 | const array = [1, 2, 3];
23 | const consoleSpy = jest.spyOn(console, 'log');
24 |
25 | ignoreFirstAndLastElement(array);
26 |
27 | expect(consoleSpy).toHaveBeenCalledTimes(1);
28 | expect(consoleSpy).toHaveBeenCalledWith(2);
29 |
30 | consoleSpy.mockRestore();
31 | });
32 |
33 | // Function receives an array with length > 3, and logs all elements except the first and last ones
34 | it('should log all elements except the first and last ones when array length is greater than 3', () => {
35 | const array = [1, 2, 3, 4, 5, 6];
36 | const consoleSpy = jest.spyOn(console, 'log');
37 |
38 | ignoreFirstAndLastElement(array);
39 |
40 | expect(consoleSpy).toHaveBeenCalledTimes(4);
41 | expect(consoleSpy).toHaveBeenCalledWith(2);
42 | expect(consoleSpy).toHaveBeenCalledWith(3);
43 | expect(consoleSpy).toHaveBeenCalledWith(4);
44 | expect(consoleSpy).toHaveBeenCalledWith(5);
45 |
46 | consoleSpy.mockRestore();
47 | });
48 |
49 | // Function receives an empty array, and logs 'Tamanho do array inválido'
50 | it(`should log 'Tamanho do array inválido' when array is empty`, () => {
51 | const array = [];
52 | const consoleSpy = jest.spyOn(console, 'log');
53 |
54 | ignoreFirstAndLastElement(array);
55 |
56 | expect(consoleSpy).toHaveBeenCalledTimes(1);
57 | expect(consoleSpy).toHaveBeenCalledWith('Tamanho do array inválido');
58 |
59 | consoleSpy.mockRestore();
60 | });
61 |
62 | // Function receives an array with length == 1, and logs 'Tamanho do array inválido'
63 | it(`should log 'Tamanho do array inválido' when array length is equal to 1`, () => {
64 | const array = [1];
65 | const consoleSpy = jest.spyOn(console, 'log');
66 |
67 | ignoreFirstAndLastElement(array);
68 |
69 | expect(consoleSpy).toHaveBeenCalledTimes(1);
70 | expect(consoleSpy).toHaveBeenCalledWith('Tamanho do array inválido');
71 |
72 | consoleSpy.mockRestore();
73 | });
74 |
75 | // Function receives an array with length == 2, and logs 'Tamanho do array inválido'
76 | it(`should log 'Tamanho do array inválido' when array length is equal to 2`, () => {
77 | const array = [1, 2];
78 | const consoleSpy = jest.spyOn(console, 'log');
79 |
80 | ignoreFirstAndLastElement(array);
81 |
82 | expect(consoleSpy).toHaveBeenCalledTimes(1);
83 | expect(consoleSpy).toHaveBeenCalledWith('Tamanho do array inválido');
84 |
85 | consoleSpy.mockRestore();
86 | });
87 | });
88 |
--------------------------------------------------------------------------------
/tests/invertElementsArray.test.js:
--------------------------------------------------------------------------------
1 | const { invertElementsArray } = require('../src/desafio1ao6')
2 |
3 | describe('4 - invertElementsArray', () => {
4 |
5 | // The function should correctly invert an array of any length.
6 | it('should correctly invert an array of any length', () => {
7 | const input = [1, 2, 3, 4, 5];
8 | const expected = [5, 4, 3, 2, 1];
9 | const result = invertElementsArray(input);
10 | expect(result).toEqual(expected);
11 | });
12 |
13 | // The function should return an empty array when given an empty array.
14 | it('should return an empty array when given an empty array', () => {
15 | const input = [];
16 | const expected = [];
17 | const result = invertElementsArray(input);
18 | expect(result).toEqual(expected);
19 | });
20 |
21 | // The function should return a new array and not modify the original array.
22 | it('should return a new array and not modify the original array', () => {
23 | const input = [1, 2, 3];
24 | const result = invertElementsArray(input);
25 | expect(result).not.toBe(input);
26 | });
27 |
28 | // The function should correctly invert an array containing only one element.
29 | it('should correctly invert an array containing only one element', () => {
30 | const input = [1];
31 | const expected = [1];
32 | const result = invertElementsArray(input);
33 | expect(result).toEqual(expected);
34 | });
35 |
36 | // The function should correctly invert an array containing only two elements.
37 | it('should correctly invert an array containing only two elements', () => {
38 | const input = [1, 2];
39 | const expected = [2, 1];
40 | const result = invertElementsArray(input);
41 | expect(result).toEqual(expected);
42 | });
43 | });
44 |
--------------------------------------------------------------------------------
/tests/invertString.test.js:
--------------------------------------------------------------------------------
1 | const { invertString } = require('../src/desafio1ao6')
2 |
3 | describe('5 - invertString', () => {
4 |
5 | // Returns the inverted version of a string with no special characters or spaces.
6 | it('should return the inverted version of a string with no special characters or spaces', () => {
7 | const result = invertString("hello");
8 | expect(result).toEqual("olleh");
9 | });
10 |
11 | // Returns the inverted version of a string with special characters and spaces.
12 | it('should return the inverted version of a string with special characters and spaces', () => {
13 | const result = invertString("hello world!");
14 | expect(result).toEqual("!dlrow olleh");
15 | });
16 |
17 | // Returns an empty string when given an empty string.
18 | it('should return an empty string when given an empty string', () => {
19 | const result = invertString("");
20 | expect(result).toEqual("");
21 | });
22 |
23 | // Returns the inverted version of a string with only one character.
24 | it('should return the inverted version of a string with only one character', () => {
25 | const result = invertString("a");
26 | expect(result).toEqual("a");
27 | });
28 |
29 | // Returns the same string when given a palindrome.
30 | it('should return the same string when given a palindrome', () => {
31 | const result = invertString("racecar");
32 | expect(result).toEqual("racecar");
33 | });
34 | });
35 |
--------------------------------------------------------------------------------
/tests/noDuplicates.test.js:
--------------------------------------------------------------------------------
1 | const { noDuplicates } = require('../src/desafio1ao6')
2 |
3 | describe('6 - noDuplicates', () => {
4 |
5 | // Returns an empty array when the input array is empty.
6 | it('should return an empty array when the input array is empty', () => {
7 | const input = [];
8 | const expected = [];
9 | const result = noDuplicates(input);
10 | expect(result).toEqual(expected);
11 | });
12 |
13 | // Returns an array with the same elements when there are no duplicates in the input array.
14 | it('should return the same array when there are no duplicates in the input array', () => {
15 | const input = [1, 2, 3, 4, 5];
16 | const expected = [1, 2, 3, 4, 5];
17 | const result = noDuplicates(input);
18 | expect(result).toEqual(expected);
19 | });
20 |
21 | // Returns an array with only the unique elements of the input array, preserving their order.
22 | it('should return an array with only the unique elements of the input array, preserving their order', () => {
23 | const input = [1, 2, 3, 2, 4, 5, 1];
24 | const expected = [1, 2, 3, 4, 5];
25 | const result = noDuplicates(input);
26 | expect(result).toEqual(expected);
27 | });
28 |
29 | // Returns an array with only one element when the input array has only one element.
30 | it('should return an array with only one element when the input array has only one element', () => {
31 | const input = [1];
32 | const expected = [1];
33 | const result = noDuplicates(input);
34 | expect(result).toEqual(expected);
35 | });
36 |
37 | // Returns an array with only one element when the input array has only duplicate elements.
38 | it('should return an array with only one element when the input array has only duplicate elements', () => {
39 | const input = [1, 1, 1, 1];
40 | const expected = [1];
41 | const result = noDuplicates(input);
42 | expect(result).toEqual(expected);
43 | });
44 |
45 | // Returns an array with only one element when the input array has all elements equal.
46 | it('should return an array with only one element when the input array has all elements equal', () => {
47 | const input = [2, 2, 2, 2, 2];
48 | const expected = [2];
49 | const result = noDuplicates(input);
50 | expect(result).toEqual(expected);
51 | });
52 | });
53 |
--------------------------------------------------------------------------------
/tests/printElements.test.js:
--------------------------------------------------------------------------------
1 | const { printElements } = require('../src/desafio1ao6');
2 |
3 | describe('1 - printElements', () => {
4 | // prints all elements of the array
5 | it('should print all elements of the array when called with a valid array', () => {
6 | const array = [1, 2, 3];
7 | const consoleSpy = jest.spyOn(console, 'log');
8 |
9 | printElements(array);
10 |
11 | expect(consoleSpy).toHaveBeenCalledTimes(3);
12 | expect(consoleSpy).toHaveBeenNthCalledWith(1, 1);
13 | expect(consoleSpy).toHaveBeenNthCalledWith(2, 2);
14 | expect(consoleSpy).toHaveBeenNthCalledWith(3, 3);
15 |
16 | consoleSpy.mockRestore();
17 | });
18 |
19 | // works with arrays of any length
20 | it('should work with arrays of any length when called with a valid array', () => {
21 | const array = [10, 5, 9, 26, 8];
22 | const consoleSpy = jest.spyOn(console, 'log');
23 |
24 | printElements(array);
25 |
26 | expect(consoleSpy).toHaveBeenCalledTimes(5);
27 | expect(consoleSpy).toHaveBeenNthCalledWith(1, 10);
28 | expect(consoleSpy).toHaveBeenNthCalledWith(2, 5);
29 | expect(consoleSpy).toHaveBeenNthCalledWith(3, 9);
30 | expect(consoleSpy).toHaveBeenNthCalledWith(4, 26);
31 | expect(consoleSpy).toHaveBeenNthCalledWith(5, 8);
32 |
33 | consoleSpy.mockRestore();
34 | });
35 |
36 | // handles arrays with one element
37 | it('should handle arrays with one element when called with a valid array', () => {
38 | const array = [1];
39 | const consoleSpy = jest.spyOn(console, 'log');
40 |
41 | printElements(array);
42 |
43 | expect(consoleSpy).toHaveBeenCalledTimes(1);
44 | expect(consoleSpy).toHaveBeenNthCalledWith(1, 1);
45 |
46 | consoleSpy.mockRestore();
47 | });
48 | // handles arrays with null or undefined values
49 | it('should handle arrays with null or undefined values when called with an array containing null and undefined values', () => {
50 | const array = [null, undefined];
51 | const consoleSpy = jest.spyOn(console, 'log');
52 |
53 | printElements(array);
54 |
55 | expect(consoleSpy).toHaveBeenCalledTimes(2);
56 | expect(consoleSpy).toHaveBeenNthCalledWith(1, null);
57 | expect(consoleSpy).toHaveBeenNthCalledWith(2, undefined);
58 |
59 | consoleSpy.mockRestore();
60 | });
61 | });
62 |
--------------------------------------------------------------------------------
/tests/taxesCalcul.test.js:
--------------------------------------------------------------------------------
1 | const { taxesCalcul } = require('../src/desafio7')
2 |
3 | describe('7 - taxesCalcul', () => {
4 |
5 | // Should return the correct net salary for a gross salary of 2000
6 | it('should return the correct net salary for a gross salary of 2000', () => {
7 | const grossSalary = 2000;
8 | const expectedNetSalary = "Salário: R$ 1820";
9 |
10 | expect(taxesCalcul(grossSalary)).toBe(expectedNetSalary);
11 | });
12 |
13 | // Should return the correct net salary for a gross salary of 3000
14 | it('should return the correct net salary for a gross salary of 3000', () => {
15 | const grossSalary = 3000;
16 | const expectedNetSalary = "Salário: R$ 2612.55";
17 |
18 | expect(taxesCalcul(grossSalary)).toBe(expectedNetSalary);
19 | });
20 |
21 | // Should return the correct net salary for a gross salary of 4000
22 | it('should return the correct net salary for a gross salary of 4000', () => {
23 | const grossSalary = 4000;
24 | const expectedNetSalary = "Salário: R$ 3380.8";
25 |
26 | expect(taxesCalcul(grossSalary)).toBe(expectedNetSalary);
27 | });
28 |
29 | // Should return 0 for a gross salary of 0
30 | it('should return 0 for a gross salary of 0', () => {
31 | const grossSalary = 0;
32 | const expectedNetSalary = "Salário: R$ 0";
33 |
34 | expect(taxesCalcul(grossSalary)).toBe(expectedNetSalary);
35 | });
36 |
37 | // Should return the correct net salary for the minimum gross salary (1045)
38 | it('should return the correct net salary for the minimum gross salary (1045)', () => {
39 | const grossSalary = 1045;
40 | const expectedNetSalary = "Salário: R$ 961.4";
41 |
42 | expect(taxesCalcul(grossSalary)).toBe(expectedNetSalary);
43 | });
44 | });
45 |
--------------------------------------------------------------------------------