Estruturas de dados e algoritmos com JavaScript 2nd Edition Groner Loiane
Estruturas de dados e algoritmos com JavaScript 2nd Edition Groner Loiane
Estruturas de dados e algoritmos com JavaScript 2nd Edition Groner Loiane
Estruturas de dados e algoritmos com JavaScript 2nd Edition Groner Loiane
1. Estruturas de dados e algoritmos com JavaScript
2nd Edition Groner Loiane install download
http://ebookstep.com/product/estruturas-de-dados-e-algoritmos-
com-javascript-2nd-edition-groner-loiane/
Download more ebook from https://ebookstep.com
2. We believe these products will be a great fit for you. Click
the link to download now, or visit ebookstep.com
to discover even more!
Lógica de Programação e Algoritmos com JavaScript uma
Introdução à Programação de Computadores com Exemplos e
Exercícios Para Iniciantes 1st Edition Edécio Fernando
Iepsen
http://ebookstep.com/product/logica-de-programacao-e-algoritmos-
com-javascript-uma-introducao-a-programacao-de-computadores-com-
exemplos-e-exercicios-para-iniciantes-1st-edition-edecio-
fernando-iepsen/
Manual de Analise de Dados Estatística e Modelagem
Multivariada com Excel SPSS e Stata 1st Edition Luiz
Paulo Fávero
http://ebookstep.com/product/manual-de-analise-de-dados-
estatistica-e-modelagem-multivariada-com-excel-spss-e-stata-1st-
edition-luiz-paulo-favero/
Computação Evolucionária Aplique os Algoritmos
Genéticos com Python e Numpy 1st Edition Eduardo
Pereira
http://ebookstep.com/product/computacao-evolucionaria-aplique-os-
algoritmos-geneticos-com-python-e-numpy-1st-edition-eduardo-
pereira/
Storytelling com Dados Cole Nussbaumer Knaflic
http://ebookstep.com/product/storytelling-com-dados-cole-
nussbaumer-knaflic/
3. Teoria Computacional de Grafos: Os algoritmos Com
programas Python 1st Edition Jayme Luiz Szwarcfiter
http://ebookstep.com/product/teoria-computacional-de-grafos-os-
algoritmos-com-programas-python-1st-edition-jayme-luiz-
szwarcfiter/
Visualização de dados com o software R 1st Edition
Luciane Ferreira Alcoforado
http://ebookstep.com/product/visualizacao-de-dados-com-o-
software-r-1st-edition-luciane-ferreira-alcoforado/
Da privacidade à proteção de dados pessoais elementos
da formação da Lei Geral de Proteção de Dados 2nd
Edition Danilo Cesar Maganhoto Doneda
http://ebookstep.com/product/da-privacidade-a-protecao-de-dados-
pessoais-elementos-da-formacao-da-lei-geral-de-protecao-de-
dados-2nd-edition-danilo-cesar-maganhoto-doneda/
LGPD Lei Geral de Proteção de Dados comentada 2nd
Edition Viviane Nóbrega Maldonado
http://ebookstep.com/product/lgpd-lei-geral-de-protecao-de-dados-
comentada-2nd-edition-viviane-nobrega-maldonado/
Lei Geral de Proteção de Dados Pessoais e suas
repercussões no direito brasileiro Ana Frazão
http://ebookstep.com/product/lei-geral-de-protecao-de-dados-
pessoais-e-suas-repercussoes-no-direito-brasileiro-ana-frazao/
7. Aos meus pais, por seu amor e assistência, e por me guiarem durante todos
esses anos.
Ao meu marido, pelo apoio e por ser o meu amado companheiro na nossa
jornada de vida.
– Loiane Groner
8. Sumário
Colaboradores
Prefácio
Capítulo 1 ■ JavaScript – uma visão geral rápida
Estrutura de dados e algoritmos em JavaScript
Configurando o ambiente
Configuração mínima para trabalhar com JavaScript
Usando servidores web
http-server do Node.js
Básico sobre o JavaScript
Variáveis
Escopo das variáveis
Operadores
Verdadeiro e falso
Funções dos operadores de igualdade (== e ===)
Estruturas de controle
Instruções condicionais
Laços
Funções
Programação orientada a objetos em Javascript
Depuração e ferramentas
Depuração com o VSCode
Resumo
Capítulo 2 ■Visão geral sobre ECMAScript eTypeScript
ECMAScript ou JavaScript?
ES6, ES2015, ES7, ES2016, ES8, ES2017 e ES.Next
Tabela de compatibilidade
Usando o Babel.js
Funcionalidades das versões ECMAScript 2015+
9. let e const no lugar de var
Escopo de variáveis com let e const
Templates literais
Funções de seta
Valores default para parâmetros de funções
Declarando os operadores de espalhamento e rest
Propriedades melhoradas de objetos
Programação orientada a objetos com classes
Herança
Trabalhando com getters e setters
Operador de exponencial
Módulos
Executando módulos ES2015 no navegador e com o Node.js
Usando importações nativas da ES2015 no Node.js
Executando módulos ES2015 no navegador
Compatibilidade de versões anteriores a ES2015+
Introdução ao TypeScript
Inferência de tipo
Interfaces
Genéricos
Outras funcionalidades do TypeScript
Verificações do TypeScript em tempo de compilação em arquivos
JavaScript
Resumo
Capítulo 3 ■ Arrays
Por que devemos usar arrays?
Criando e inicializando arrays
Acessando elementos e fazendo uma iteração em um array
Acrescentando elementos
Inserindo um elemento no final do array
Usando o método push
Inserindo um elemento na primeira posição
Usando o método unshift
Removendo elementos
Removendo um elemento do final do array
10. Removendo um elemento da primeira posição
Usando o método shift
Adicionando e removendo elementos de uma posição específica
Arrays bidimensionais e multidimensionais
Iterando pelos elementos de arrays bidimensionais
Arrays multidimensionais
Referências para métodos de array em JavaScript
Juntando vários arrays
Funções de iteração
Iterando com o método every
Iterando com o método some
Iterando com forEach
Usando map e filter
Usando o método reduce
ECMAScript 6 e as novas funcionalidades de array
Iterando com o laço for…of
Usando o objeto @@iterator
Métodos entries, keys e values de array
Usando o método from
Usando o método Array.of
Usando o método fill
Usando o método copyWithin
Ordenando elementos
Ordenação personalizada
Ordenando strings
Pesquisa
ECMAScript 2015 – os métodos find e findIndex
ECMAScript 2016 – usando o método includes
Convertendo um array em uma string
Classe TypedArray
Arrays em TypeScript
Resumo
Capítulo 4 ■ Pilhas
Criação de uma biblioteca de estruturas de dados e algoritmos JavaScript
Estrutura de dados de pilha
11. Criando uma classe Stack baseada em array
Push de elementos na pilha
Pop de elementos da pilha
Dando uma espiada no elemento que está no topo da pilha
Verificando se a pilha está vazia
Limpando os elementos da pilha
Usando a classe Stack
Criando uma classe JavaScript Stack baseada em objeto
Push de elementos na pilha
Verificando se a pilha está vazia e o seu tamanho
Pop de elementos da pilha
Dando uma espiada no topo e limpando a pilha
Criando o método toString
Protegendo os elementos internos da estrutura de dados
Convenção de nomenclatura com underscore
Classes ES2015 com símbolos no escopo
Classes ES2015 com WeakMap
Proposta para campos de classe na ECMAScript
Resolvendo problemas usando pilhas
Convertendo números decimais para binários
Algoritmo conversor de base
Resumo
Capítulo 5 ■ Filas e deques
Estrutura de dados de fila
Criando a classe Queue
Inserção de elementos na fila
Remoção de elementos da fila
Dando uma espiada no elemento que está na frente da fila
Verificando se a pilha está vazia e o seu tamanho
Limpando a fila
Criando o método toString
Usando a classe Queue
Estrutura de dados de deque
Criando a classe Deque
Adicionando elementos na frente do deque
12. Usando a classe Deque
Resolvendo problemas usando filas e deques
Fila circular – Batata Quente
Verificador de palíndromo
Filas de tarefas em JavaScript
Resumo
Capítulo 6 ■ Listas ligadas
Estrutura de dados da lista ligada
Criando a classe LinkedList
Inserindo elementos no final da lista ligada
Removendo elementos de uma posição específica da lista ligada
Percorrendo a lista com um laço até alcançar a posição desejada
Refatorando o método remove
Inserindo um elemento em qualquer posição
Método indexOf: devolvendo a posição de um elemento
Removendo um elemento da lista ligada
Métodos isEmpty, size e getHead
Método toString
Listas duplamente ligadas
Inserindo um novo elemento em qualquer posição
Removendo elementos de qualquer posição
Listas ligadas circulares
Inserindo um novo elemento em qualquer posição
Removendo elementos de qualquer posição
Listas ligadas ordenadas
Inserindo elementos na ordem
Criando a classe StackLinkedList
Resumo
Capítulo 7 ■ Conjuntos
Estruturando um conjunto de dados
Criando uma classe Set
Método has(element)
Método add
Métodos delete e clear
13. Método size
Método values
Usando a classe Set
Operações em conjuntos
União de conjuntos
Intersecção de conjuntos
Aperfeiçoando o método intersection
Diferença entre conjuntos
Subconjunto
ECMAScript 2015 – a classe Set
Operações com a classe Set da ES2015
Simulando a operação de união
Simulando a operação de intersecção
Simulando a operação de diferença
Usando o operador de espalhamento
Multiconjuntos ou bags
Resumo
Capítulo 8 ■ Dicionários e hashes
Estrutura de dados de dicionário
Criando a classe Dictionary
Verificando se uma chave está presente no dicionário
Definindo uma chave e um valor no dicionário, e a classe ValuePair
Removendo um valor do dicionário
Obtendo um valor do dicionário
Métodos keys, values e valuePairs
Iterando pelos ValuePairs do dicionário com forEach
Métodos clear, size, isEmpty e toString
Usando a classe Dictionary
Tabela hash
Criando uma classe HashTable
Criando uma função de hash
Inserindo uma chave e um valor na tabela hash
Obtendo um valor da tabela hash
Removendo um valor da tabela hash
Usando a classe HashTable
14. Tabela hash versus conjunto hash
Tratando colisões nas tabelas hash
Encadeamento separado
Método put
Método get
Método remove
Sondagem linear
Método put
Método get
Método remove
Criando funções melhores de hash
Classe Map da ES2015
Classes WeakMap e WeakSet da ES2015
Resumo
Capítulo 9 ■ Recursão
Entendendo a recursão
Calculando o fatorial de um número
Fatorial iterativo
Fatorial recursivo
Pilha de chamadas
Limitação do tamanho da pilha de chamadas em JavaScript
Sequência de Fibonacci
Fibonacci iterativo
Fibonacci recursivo
Fibonacci com memoização
Por que usar recursão? É mais rápido?
Resumo
Capítulo 10 ■ Árvores
Estrutura de dados de árvore
Terminologia de árvores
Árvore binária e árvore binária de busca
Criando as classes Node e BinarySearchTree
Inserindo uma chave na BST
Percorrendo uma árvore
15. Percurso em-ordem
Percurso pré-ordem
Percurso pós-ordem
Pesquisando valores em uma árvore
Pesquisando valores mínimos e máximos
Pesquisando um valor específico
Removendo um nó
Removendo uma folha
Removendo um nó com um filho à esquerda ou à direita
Removendo um nó com dois filhos
Árvores autobalanceadas
Árvore de Adelson-Velskii e Landi (árvore AVL)
Altura de um nó e o fator de balanceamento
Operações de balanceamento – rotações na árvore AVL
Rotação Esquerda-Esquerda: rotação simples à direita
Rotação Direita-Direita: rotação simples à esquerda
Esquerda-Direita: rotação dupla à direita
Direita-Esquerda: rotação dupla à esquerda
Inserindo um nó na árvore AVL
Removendo um nó da árvore AVL
Árvore rubro-negra
Inserindo um nó na árvore rubro-negra
Verificando as propriedades da árvore rubro-negra após a inserção
Rotações na árvore rubro-negra
Resumo
Capítulo 11 ■ Heap binário e heap sort
Estrutura de dados do heap binário
Criando a classe MinHeap
Representação da árvore binária com um array
Inserindo um valor no heap
Operação de sift up
Encontrando os valores mínimo e máximo no heap
Extraindo os valores mínimo e máximo do heap
Operação de sift down
Criando a classe MaxHeap
16. Algoritmo de heap sort
Resumo
Capítulo 12 ■ Grafos
Terminologia dos grafos
Grafos direcionados e não direcionados
Representando um grafo
A matriz de adjacências
Lista de adjacências
Matriz de incidências
Criando a classe Graph
Percorrendo grafos
Busca em largura (BFS)
Encontrando os caminhos mais curtos usando BFS
Estudos adicionais sobre algoritmos de caminhos mais curtos
Busca em profundidade (DFS)
Explorando o algoritmo DFS
Ordenação topológica usando DFS
Algoritmos de caminho mais curto
Algoritmo de Dijkstra
Algoritmo de Floyd-Warshall
Árvore de extensão mínima (MST)
Algoritmo de Prim
Algoritmo de Kruskal
Resumo
Capítulo 13 ■ Algoritmos de ordenação e de busca
Algoritmos de ordenação
Bubble sort
Bubble sort melhorado
Selection sort
Insertion sort
Merge sort
Quick sort
Processo de partição
Quick sort em ação
17. Counting sort
Bucket sort
Radix sort
Algoritmos de busca
Busca sequencial
Busca binária
Busca por interpolação
Algoritmos de embaralhamento
Algoritmo de embaralhamento de Fisher-Yates
Resumo
Capítulo 14 ■ Designs de algoritmos e técnicas
Dividir e conquistar
Busca binária
Programação dinâmica
Problema do número mínimo de moedas para troco
Problema da mochila
Maior subsequência comum
Multiplicação de cadeia de matrizes
Algoritmos gulosos
Problema do número mínimo de moedas para troco
Problema fracionário da mochila
Algoritmos de backtracking
Rato em um labirinto
Solucionador de sudoku
Introdução à programação funcional
Programação funcional versus programação imperativa
ES2015+ e a programação funcional
Caixa de ferramentas funcional de JavaScript – map, filter e reduce
Bibliotecas e estruturas de dados funcionais de JavaScript
Resumo
Capítulo 15 ■ Complexidade de algoritmos
Notação big-O
Compreendendo a notação big-O
O(1)
18. O(n)
O(n2)
Comparando as complexidades
Estruturas de dados
Grafos
Algoritmos de ordenação
Algoritmos de busca
Introdução à teoria de NP-completo
Problemas impossíveis e algoritmos heurísticos
Divertindo-se com algoritmos
Resumo
19. Colaboradores
Sobre a autora
Loiane Groner tem mais de dez anos de experiência no desenvolvimento
de aplicações corporativas. Atualmente, trabalha como analista de
negócios e desenvolvedora de Java/HTML5/JavaScript em uma instituição
financeira norte-americana.
É apaixonada por tecnologia, publica artigos em seu blog e ministra
palestras em conferências sobre Java, ExtJS, Cordova, Ionic, TypeScript e
Angular.
É Google Developer Expert em Web Technologies (Tecnologias Web) e
Angular, e Microsoft Most Valuable Professional em Visual Studio e
Development Technologies (Tecnologias de Desenvolvimento). É também
autora de outros livros da Packt.
Gostaria de agradecer aos meus pais a educação, a orientação e os conselhos
que me deram por todos esses anos, e ao meu marido por ser paciente e me
apoiar, incentivando-me para que eu continue fazendo o que amo.
Também gostaria de agradecer aos leitores deste e de outros livros que escrevi
o apoio e o feedback. Muito obrigada!
Sobre os revisores
Todd Zebert é desenvolvedor web full stack e trabalha atualmente na
Miles.
Já foi revisor técnico de vários livros e vídeos, é palestrante frequente em
conferências sobre JavaScript, Drupal e tecnologias relacionadas, além de
ter um blog de tecnologia na Medium.
Tem experiência prévia diversificada em tecnologia, incluindo
infraestrutura, engenharia de rede, gerenciamento de projetos e liderança
em TI. Começou a trabalhar com desenvolvimento web no navegador
Mosaic original.
É empreendedor e faz parte da comunidade de startups de Los Angeles.
Acredita em trabalhos voluntários, código aberto, maker/STEM/STEAM e
20. em retribuição à comunidade.
Kashyap Mukkamala é um arquiteto de software entusiasmado, trabalha
na Egen Solutions Inc. e é autor do livro Hands-On Data Structures and
Algorithms with JavaScript. Quando não está resolvendo problemas de
empresas Fortune 500 na Egen, Kashyap concentra-se em construir a web
do futuro e, com isso, está ajudando a comunidade a crescer e a aprender.
21. Prefácio
JavaScript, uma das linguagens de programação mais populares
atualmente, é conhecida como a linguagem da internet porque os
navegadores a entendem de modo nativo, sem a instalação de qualquer
plugin. A linguagem JavaScript evoluiu muito, a ponto de não ser mais
apenas uma linguagem de frontend; nos dias de hoje, ela está igualmente
presente no servidor (NodeJS), no banco de dados (MongoDB) e em
dispositivos móveis, além de ser usada em dispositivos embarcados e na
Iot (Internet of Things, ou Internet das Coisas).
Conhecer as estruturas de dados é muito importante para qualquer
profissional da área de tecnologia.Trabalhar como desenvolvedor significa
ser capaz de resolver problemas com a ajuda das linguagens de
programação, e as estruturas de dados são uma parte indispensável das
soluções que precisamos criar para resolver esses problemas. Escolher
uma estrutura de dados incorreta também pode impactar o desempenho
do programa que escrevemos. Por isso, é importante conhecer as
diferentes estruturas de dados e saber aplicá-las de forma apropriada.
Os algoritmos são o estado da arte em ciência da computação. Há muitas
maneiras de resolver o mesmo problema, e algumas abordagens são
melhores que outras.
É por isso que conhecer os algoritmos mais famosos também é muito
importante.
Este livro foi escrito para iniciantes que queiram conhecer estruturas de
dados e algoritmos, mas também para aqueles que já tenham
familiaridade com eles, mas desejem conhecê-los usando JavaScript.
Boa programação!
A quem este livro se destina
Se você é estudante de ciência da computação ou está iniciando a sua
carreira na área de tecnologia e quer explorar os melhores recursos de
JavaScript, este livro foi escrito para você. Se já tem familiaridade com
programação, mas quer aperfeiçoar suas habilidades com algoritmos e
22. estruturas de dados, este livro também foi feito para você.
Basta ter conhecimento básico de JavaScript e de lógica de programação
para começar a se divertir com os algoritmos.
O que este livro inclui
O Capítulo 1, JavaScript – uma visão geral rápida, apresenta o básico sobre
JavaScript, aquilo que devemos conhecer antes de ver as estruturas de
dados e os algoritmos. Além disso, aborda a configuração do ambiente de
desenvolvimento de que precisaremos neste livro.
O Capítulo 2, Visão geral sobre ECMAScript e TypeScript, aborda algumas
funcionalidades novas de JavaScript introduzidas a partir de 2015, além de
incluir as funcionalidades básicas do TypeScript, um superconjunto do
JavaScript.
O Capítulo 3, Arrays, explica como usar a estrutura de dados mais básica
e mais utilizada, os arrays. Esse capítulo mostra como declarar, inicializar,
adicionar e remover elementos de um array. Também aborda o uso dos
métodos do Array nativo de JavaScript.
O Capítulo 4, Pilhas, apresenta a estrutura de dados de pilha, mostrando
como criar, adicionar e remover elementos dela. Também mostra como
usar pilhas para resolver alguns problemas relacionados à ciência da
computação.
O Capítulo 5, Filas e deques, apresenta a estrutura de dados de fila,
mostrando como criar, adicionar e remover elementos dela. Inclui a
estrutura de dados deque (fila de duas pontas), um tipo especial de fila.
Também mostra como usar filas para resolver alguns problemas
relacionados à ciência da computação e explica as principais diferenças
entre filas e pilhas.
O Capítulo 6, Listas ligadas, explica como criar a estrutura de dados de
lista ligada a partir do zero, usando objetos e o conceito de “ponteiro”
.
Além de descrever como declarar, criar, adicionar e remover elementos, o
capítulo também inclui os vários tipos de listas ligadas, como as listas
duplamente ligadas e as listas ligadas circulares.
O Capítulo 7, Conjuntos, apresenta a estrutura de dados de conjunto e
como podemos usá-la para armazenar elementos não repetidos. Também
explica os diferentes tipos de operações de conjunto e como implementá-
23. los e usá-los.
O Capítulo 8, Dicionários e hashes, explica as estruturas de dados de
dicionários e hashes e as diferenças entre eles. Esse capítulo descreve
como declarar, criar e usar as duas estruturas de dados. Além disso,
explica como tratar colisões de hash e descreve técnicas para criar funções
melhores de hash.
O Capítulo 9, Recursão, apresenta o conceito de recursão e mostra as
diferenças entre algoritmos declarativos e recursivos.
O Capítulo 10, Árvores, descreve a estrutura de dados de árvore e a sua
terminologia, concentrando-se nos dados da Árvore Binária de Busca
(Binary Search Tree) – em seus métodos para pesquisar, percorrer,
adicionar e remover nós. Também apresenta as árvores autobalanceadas,
como a AVL e a Rubro-Negra (Red-Black).
O Capítulo 11, Heap binário e Heap sort, aborda as estruturas de dados de
min heap e max heap, apresenta como usar o heap como uma fila de
prioridades e discute o famoso algoritmo heap sort.
O Capítulo 12, Grafos, explica o mundo maravilhoso dos grafos e suas
aplicações em problemas do mundo real. Apresenta a terminologia mais
comum associada aos grafos, as diferentes maneiras de representá-los e
como percorrê-los usando os algoritmos BFS (Breadth-First-Search, ou
Busca em Largura) e DFS (Depth-First-Search, ou Busca em
Profundidade) e suas aplicações.
O Capítulo 13, Algoritmos de ordenação e de busca, explora os algoritmos
mais usados de ordenação, como o bubble sort (ordenação por flutuação
– e a sua versão melhorada), o selection sort (ordenação por seleção), o
insertion sort (ordenação por inserção), o merge sort (ordenação por
mistura) e o quick sort (ordenação rápida). Também inclui o counting
sort (ordenação por contagem) e o radix sort (ordenação de raízes), dois
algoritmos de ordenação distribuídos. Além disso, discute como
funcionam os algoritmos de busca, como os de busca sequencial e de
busca binária, e como embaralhar arrays.
O Capítulo 14, Designs de algoritmos e técnicas, apresenta algumas técnicas
de algoritmos, além de descrever alguns dos algoritmos mais famosos.
Também inclui uma introdução à programação funcional em JavaScript.
O Capítulo 15, Complexidade de algoritmos, apresenta a notação big-O (O
24. grande) e seus conceitos, além de incluir uma “colinha” com a
complexidade dos algoritmos implementados neste livro. Inclui também
uma introdução aos problemas NP-completos e às soluções heurísticas.
Por fim, o capítulo explica como levar o seu conhecimento sobre
algoritmos para o próximo patamar.
Para aproveitar ao máximo este livro
Embora este livro inclua uma rápida introdução ao JavaScript em seu
primeiro capítulo, você precisará ter um conhecimento básico dessa
linguagem e de lógica de programação.
Para testar os exemplos de código apresentados, você precisará de um
editor de código (como o Atom ou o Visual Studio Code) para ler o
código, além de um navegador (Chrome, Firefox ou Edge).
Também poderá testar os exemplos online acessando https://javascript-
ds-algorithms-book.firebaseapp.com/. Lembre-se também de abrir as
ferramentas do desenvolvedor no navegador para que veja o que está
sendo gerado como saída no console.
Convenções usadas
Há uma série de convenções textuais usadas neste livro.
CódigoNoTexto: indica palavras referentes a código no texto, nomes de
tabelas de banco de dados, nomes de pastas, nomes e extensões de
arquivos, nomes de path, URLs dummy, entrada de usuário e handles do
Twitter. Eis um exemplo: “Monte o arquivo baixado WebStorm-10*.dmg
contendo a imagem de disco como outro disco em seu sistema.”
Um bloco de código é apresentado assim:
class Stack {
constructor() {
this.items = []; // {1}
}
}
Se quisermos chamar a sua atenção para uma parte específica de um
bloco de código, as linhas ou itens relevantes estarão em negrito:
const stack = new Stack();
console.log(stack.isEmpty()); // exibe true
25. Qualquer entrada ou saída na linha de comando será apresentada assim:
npm install http-server -g
Negrito: indica um termo novo, uma palavra importante ou palavras que
você vê na tela. Por exemplo, palavras em menus ou em caixas de diálogo
aparecem no texto dessa forma. Eis um exemplo: “Selecione System info
(Info sobre o sistema) no painel Administration (Administração).”
Dicas e truques aparecerão desta forma.
Avisos ou notas importantes serão indicados assim.
Como entrar em contato conosco
Envie seus comentários e suas dúvidas sobre este livro à editora pelo
email: novatec@novatec.com.br.
Temos uma página web para este livro, na qual incluímos erratas,
exemplos e quaisquer outras informações adicionais.
• Página da edição traduzida para o português
https://www.novatec.com.br/livros/estruturas-de-dados-algoritmos-em-
javascript-2ed/
• Página da edição original em inglês
https://www.packtpub.com/web-development/learning-javascript-data-
structures-and-algorithms-third-edition
• Código-fonte dos exemplos no GitHub
https://github.com/PacktPublishing/Learning-JavaScript-Data-Structures-
and-Algorithms-Third-Edition.
Para obter mais informações sobre os livros da Novatec, acesse nosso site
em: http://www.novatec.com.br.
26. capítulo 1
JavaScript – uma visão geral rápida
A linguagem JavaScript é extremamente eficaz, sendo uma das mais
populares do mundo e uma das mais proeminentes na internet. Por
exemplo, o GitHub (o maior host de códigos do mundo, disponível em
https://github.com) hospeda mais de 400 mil repositórios de JavaScript (a
maior parte dos projetos disponíveis está em JavaScript; consulte
http://githut.info). O número de projetos em JavaScript e no GitHub
aumenta a cada ano.
A linguagem JavaScript não é usada apenas no frontend. Ela também
pode ser utilizada no backend, sendo o Node.js a tecnologia responsável
por isso. O número de npms (Node Package Modules, ou Módulos do
Pacote Node), disponíveis em https://www.npmjs.org, também tem crescido
exponencialmente. Além disso, o JavaScript pode ser usado em
desenvolvimento para dispositivos móveis, e é um dos frameworks mais
populares no Apache Cordova (https://cordova.apache.org), um
framework híbrido para dispositivos móveis, o qual permite que os
desenvolvedores programem usando HTML, CSS e JavaScript,
possibilitando construir um aplicativo e gerar um arquivo APK para
Android e IPA para iOS (Apple). E, claro, não vamos nos esquecer das
aplicações desktop. Podemos escrever aplicações desktop compatíveis com
Linux, Mac OS e Windows usando um framework JavaScript chamado
Electron (https://electron.atom.io). O JavaScript também é usado em
dispositivos embarcados e dispositivos para IoT (Internet of Things, ou
Internet das Coisas). Como você pode ver, o JavaScript está em todos os
lugares!
Assim, se você é ou vai ser um desenvolvedor web, é mandatório ter essa
linguagem em seu currículo.
Neste capítulo, conheceremos a sintaxe e algumas funcionalidades básicas
necessárias para usar Javascript, a fim de começarmos a desenvolver a
nossa própria estrutura de dados e os nossos algoritmos. Discutiremos os
seguintes assuntos:
27. • configuração do ambiente e o básico sobre JavaScript;
• estruturas de controle e funções;
• programação orientada a objetos em Javascript;
• depuração e ferramentas.
Estrutura de dados e algoritmos em JavaScript
Neste livro, conheceremos as estruturas de dados e os algoritmos mais
usados. Por que devemos usar JavaScript para conhecê-los? Já
respondemos a essa pergunta. Além de muito popular, a linguagem
JavaScript é apropriada para conhecer as estruturas de dados por ser uma
linguagem funcional. Além do mais, essa pode ser uma maneira muito
divertida de aprender algo novo, pois é muito diferente (e mais fácil) em
comparação a conhecer as estruturas de dados com uma linguagem
padrão como C, Java ou Python. E quem disse que estruturas de dados e
algoritmos foram feitos apenas para linguagens como C e Java? Talvez
você precise fazer implementações em algumas dessas linguagens
enquanto desenvolve o frontend também.
Conhecer as estruturas de dados e os algoritmos é muito importante. O
primeiro motivo é o fato de as estruturas de dados e os algoritmos serem
capazes de resolver os problemas mais comuns de modo eficiente. Isso fará
diferença na qualidade do código-fonte que você escreverá no futuro
(inclusive no desempenho; se você escolher a estrutura de dados ou o
algoritmo incorreto, conforme o cenário, poderá ter alguns problemas de
desempenho). Em segundo lugar, os algoritmos são estudados nas
faculdades, junto com os conceitos introdutórios de ciência da
computação. Por fim, se você planeja conseguir um emprego em uma das
maiores empresas de TI (Information Technology, ou Tecnologia da
Informação) – como Google, Amazon, Microsoft, eBay e outras –, as
estruturas de dados e os algoritmos serão assuntos das perguntas nas
entrevistas.
Vamos começar!
Configurando o ambiente
Um dos prós da linguagem JavaScript, quando comparada com outras
linguagens, é que você não precisa instalar nem configurar um ambiente
28. complicado para começar a usá-la. Todo computador já tem o ambiente
necessário, mesmo que um usuário jamais chegue a escrever uma única
linha de código-fonte.Tudo que precisamos é de um navegador!
Para executar os exemplos deste livro, é recomendável ter um navegador
moderno instalado, como o Google Chrome ou o Firefox (você pode usar
aquele de que mais gosta), um editor de sua preferência (como o Visual
Studio Code) e um servidor web (XAMPP ou qualquer outro de sua
preferência, mas esse passo é opcional). O Chrome, o Firefox, o VS Code e
o XAMPP estão disponíveis para Windows, Linux e Mac OS.
Configuração mínima para trabalhar com JavaScript
O ambiente mais simples que você pode usar para desenvolvimento com
JavaScript é um navegador. Os navegadores modernos (Chrome, Firefox,
Safari e Edge) têm uma funcionalidade chamada Developer Tools
(Ferramentas do desenvolvedor). Para acessar o DevTools no Chrome
(Figura 1.1), clique no menu no canto superior direito, More Tools
| Developer Tools (Mais ferramentas | Ferramentas do desenvolvedor):
Figura 1.1
Ao abrir o DevTools, você verá a aba Console e poderá escrever todo o seu
código JavaScript na área de linha de comando, conforme mostra a Figura
29. 1.2 (para executar o código-fonte, é necessário teclar Enter):
Figura 1.2
Usando servidores web
A segunda opção de ambiente que você pode querer instalar em seu
computador também é simples, mas exige a instalação de um servidor
web. Se um arquivo HTML contiver somente código JavaScript simples,
que não exija nenhuma requisição para um servidor (chamadas Ajax), ele
poderá ser executado no navegador clicando com o botão direito do
mouse no arquivo HTML e selecionando a opção Open with (Abrir com).
O código que desenvolveremos neste livro é simples e poderá ser
executado usando essa abordagem. No entanto, é sempre bom ter um
servidor web instalado.
Há muitas opções gratuitas e de código aberto disponíveis. Se você tem
familiaridade com PHP, o XAMPP (https://www.apachefriends.org) é uma
boa opção, e está disponível para Linux,Windows e Mac OS.
Como o nosso foco estará no JavaScript do lado do servidor e no
navegador, há também um servidor web mais simples que você poderá
instalar no Chrome. É a extensão Web Server for Chrome, que pode ser
baixada a partir de https://goo.gl/pxqLmU. Depois de instalá-la, é possível
acessá-la por meio do URL chrome://apps: no Chrome (Figura 1.3).
Depois de abrir a extensão Web Server (Figura 1.4), você poderá escolher a
pasta que quer servir no navegador, com a opção CHOOSE
FOLDER (Selecionar pasta). É possível criar uma pasta na qual execute o
30. código-fonte que implementaremos neste livro, ou fazer o download do
código-fonte deste livro, extraí-lo em um diretório de sua preferência e
acessá-lo por meio do URL informado (o default é http://127.0.0.1:8887):
Figura 1.3
Figura 1.4
Todos os exemplos deste livro podem ser executados acessando
http://127.0.0.1:8887/examples. Você encontrará um index.html com uma
lista de todos os exemplos, conforme mostra a Figura 1.5.
31. Ao executar os exemplos, lembre-se sempre de ter o Developer Tools ativado e a
aba Console aberta para ver a saída. A extensão Web Server for Chrome também
foi desenvolvida com JavaScript. A fim de ter uma experiência melhor, é
recomendável usar essa extensão para executar os exemplos deste livro ou instalar
o http-server do Node.js, que será visto na próxima seção.
Figura 1.5
http-server do Node.js
A terceira opção é ter um ambiente 100% JavaScript! Para esse ambiente,
precisamos do Node.js instalado. Acesse http://nodejs.org, faça o
download e instale o Node.js. Depois de instalá-lo, abra a aplicação de
Terminal (se estiver usando Windows, abra o Prompt de Comandos com o
Node.js, instalado com ele) e execute o comando a seguir:
npm install http-server -g
Certifique-se de ter digitado o comando, em vez de copiá-lo e colá-lo. Se
você copiar o comando, alguns erros poderão ocorrer. É possível também
executar o comando como administrador. Em sistemas Linux e Mac, use
o seguinte comando:
sudo npm install http-server -g
32. O comando instalará o http-server, um servidor JavaScript. Para iniciar
um servidor e executar os exemplos deste livro na aplicação de Terminal,
mude o diretório para a pasta que contém o código-fonte do livro e digite
http-server, como mostra a Figura 1.6.
Para executar os exemplos, abra o navegador e acesse o localhost na porta
especificada pelo comando http-server.
Figura 1.6
Passos detalhados para fazer o download do pacote de código e executar os
exemplos foram mencionados no prefácio deste livro. Por favor, consulte esse texto.
O pacote de código do livro também está disponível no GitHub em
https://github.com/loiane/javascript-datastructures-algorithms.
Básico sobre o JavaScript
Antes de mergulhar de cabeça nas diversas estruturas de dados e
algoritmos, vamos apresentar uma visão geral rápida da linguagem
JavaScript. Esta seção apresentará o básico sobre JavaScript, necessário
para implementar os algoritmos que criaremos nos capítulos
subsequentes.
Para começar, vamos observar duas maneiras diferentes de usar o código
JavaScript em uma página HTML. O primeiro exemplo é demonstrado
pelo código a seguir. Precisamos criar um arquivo HTML (01-
HelloWorld.html) e escrever o código aí. Nesse exemplo, declaramos a tag
script no arquivo HTML e, dentro dessa tag, temos o código JavaScript:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
33. <script>
alert('Hello, World!');
</script>
</body>
</html>
Experimente usar a extensão Web Server for Chrome ou o http-server para
executar o código anterior e veja a sua saída no navegador.
Para o segundo exemplo, precisamos criar um arquivo JavaScript
(podemos salvá-lo como 01-HelloWorld.js) e, nesse arquivo, inserir o
código a seguir:
alert('Hello, World!');
Então, o nosso arquivo HTML terá um aspecto semelhante a este:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="01-HelloWorld.js"></script>
</body>
</html>
O segundo exemplo mostra como incluir um arquivo JavaScript em um
arquivo HTML.
Se executarmos qualquer um desses dois exemplos, a saída será a mesma.
No entanto, o segundo exemplo é o mais usado pelos desenvolvedores
JavaScript.
Você poderá encontrar instruções include de JavaScript ou código JavaScript na
tag head em alguns exemplos na internet. Seguindo a melhor prática, incluiremos
qualquer código JavaScript no final da tag body. Desse modo, o navegador fará o
parse do HTML, e ele será exibido antes de os scripts serem carregados. Com isso,
a página terá um melhor desempenho.
Variáveis
As variáveis armazenam dados que podem ser definidos, atualizados e
34. recuperados sempre que necessário. Os valores atribuídos a uma variável
têm um tipo. Em JavaScript, os tipos disponíveis são: number (número),
string, boolean (booleano), function (função) e object (objeto). Também
temos undefined (indefinido) e null (nulo), junto com arrays, datas e
expressões regulares.
Embora a linguagem JavaScript tenha diferentes tipos de variáveis
disponíveis, ela não é fortemente tipada como C/C++, C# e Java. Em
linguagens fortemente tipadas, devemos definir o tipo da variável em sua
declaração (em Java, por exemplo, para declarar uma variável inteira,
usamos int num = 1;). Em JavaScript, basta usar a palavra reservada var;
não é necessário declarar o tipo da variável. Por esse motivo, a linguagem
JavaScript não é fortemente tipada. Entretanto, há discussões e uma
especificação em versão preliminar para uma tipagem estática opcional
(https://github.com/dslomov/typed-objects-es7), que poderá se tornar parte
da especificação de JavaScript (ECMAScript) no futuro. Também
podemos usar o TypeScript se quisermos definir tipos para nossas
variáveis ao trabalhar com JavaScript. Conheceremos melhor a
ECMAScript e o TypeScript mais adiante neste capítulo.
A seguir, apresentamos um exemplo de uso de variáveis em JavaScript:
var num = 1; // {1}
num = 3; // {2}
var price = 1.5; // {3}
var myName = 'Packt'; // {4}
var trueValue = true; // {5}
var nullVar = null; // {6}
var und; // {7}
• Na linha {1}, temos um exemplo de como declarar uma variável em
JavaScript (estamos declarando um número). Embora não seja
necessário fazer a declaração com a palavra reservada var, especificá-la
sempre que estivermos declarando uma nova variável é uma boa
prática.
• Na linha {2}, atualizamos uma variável existente. A linguagem
JavaScript não é fortemente tipada. Isso significa que podemos declarar
uma variável, inicializá-la com um número e depois atualizá-la com
uma string ou com qualquer outro tipo de dado. Atribuir um valor a
uma variável cujo tipo seja diferente de seu tipo original também não é
35. uma boa prática.
• Na linha {3}, declaramos igualmente um número, porém, dessa vez, é
um número decimal de ponto flutuante.
• Na linha {4}, declaramos uma string; na linha {5}, declaramos um
booleano. Na linha {6}, declaramos um valor null e, na linha {7},
declaramos uma variável undefined.
• Um valor null quer dizer sem valor, e undefined significa uma variável
que foi declarada, mas que ainda não recebeu nenhum valor.
Se quisermos ver o valor de cada variável que declaramos, podemos usar
console.log para isso, conforme listado no trecho de código a seguir:
console.log('num: ' + num);
console.log('myName: ' + myName);
console.log('trueValue: ' + trueValue);
console.log('price: ' + price);
console.log('nullVar: ' + nullVar);
console.log('und: ' + und);
O método console.log também aceita mais do que apenas argumentos.
Em vez de console.log('num: ' + num), também podemos usar
console.log('num: ', num). Enquanto a primeira opção concatenará o
resultado em uma única string, a segunda nos permite adicionar uma
descrição e visualizar o conteúdo da variável caso ela seja um objeto.
Há três maneiras de exibir valores de saída em JavaScript, que poderão ser
usadas nos exemplos deste livro. A primeira é alert('My text here'), que
apresenta uma janela de alerta no navegador; a segunda é console.log('My
text here'), que exibe um texto na aba Console da ferramenta de depuração
(Google Developer Tools ou Firebug, conforme o navegador que você estiver
usando). A terceira é exibir o valor diretamente na página HTML sendo renderizada
pelo navegador, usando document.write('My text here'). Você pode usar a
opção com a qual se sentir mais à vontade.
Discutiremos as funções e os objetos mais adiante neste capítulo.
Escopo das variáveis
O escopo se refere ao local em que podemos acessar a variável no
algoritmo (também pode ser em uma função quando trabalhamos com
escopos de função).As variáveis podem ser locais ou globais.
36. Vamos observar um exemplo:
var myVariable = 'global';
myOtherVariable = 'global';
function myFunction() {
var myVariable = 'local';
return myVariable;
}
function myOtherFunction() {
myOtherVariable = 'local';
return myOtherVariable;
}
console.log(myVariable); //{1}
console.log(myFunction()); //{2}
console.log(myOtherVariable); //{3}
console.log(myOtherFunction()); //{4}
console.log(myOtherVariable); //{5}
O código anterior pode ser explicado assim:
• A linha {1} exibirá global porque estamos referenciando uma variável
global.
• A linha {2} exibirá local porque declaramos a variável myVariable
dentro da função myFunction como uma variável local, portanto o
escopo está apenas no interior de myFunction.
• A linha {3} exibirá global porque estamos referenciando a variável
global chamada myOtherVariable, inicializada na segunda linha do
exemplo.
• A linha {4} exibirá local. Na função myOtherFunction, referenciamos a
variável global myOtherVariable e lhe atribuímos o valor local, pois não
declaramos a variável usando a palavra reservada var.
• Por esse motivo, a linha {5} exibirá local (pois alteramos o valor da
variável em myOtherFunction).
Talvez você ouça falar que variáveis globais em JavaScript são prejudiciais,
e isso é verdade. Em geral, a qualidade do código-fonte JavaScript é
avaliada de acordo com o número de variáveis e funções globais (um
número elevado é ruim). Portanto, sempre que possível, procure evitar as
variáveis globais.
37. Operadores
Precisamos de operadores quando realizamos qualquer operação em uma
linguagem de programação. A linguagem JavaScript também tem
operadores aritméticos, de atribuição, de comparação, lógicos, bit a bit
(bitwise) e unários, entre outros.Vamos observar esses operadores:
var num = 0; // {1}
num = num + 2;
num = num * 3;
num = num / 2;
num++;
num--;
num += 1; // {2}
num -= 2;
num *= 3;
num /= 2;
num %= 3;
console.log('num == 1 : ' + (num == 1)); // {3}
console.log('num === 1 : ' + (num === 1));
console.log('num != 1 : ' + (num != 1));
console.log('num > 1 : ' + (num > 1));
console.log('num < 1 : ' + (num < 1));
console.log('num >= 1 : ' + (num >= 1));
console.log('num <= 1 : ' + (num <= 1));
console.log('true && false : ' + (true && false)); // {4}
console.log('true || false : ' + (true || false));
console.log('!true : ' + (!true));
Na linha {1}, temos os operadores aritméticos. Na tabela a seguir,
apresentamos os operadores e suas descrições:
Operador
aritmético
Descrição
+ Adição
- Subtração
* Multiplicação
/ Divisão
%
Módulo (resto de uma operação de
divisão)
38. Operador
aritmético
Descrição
++ Incremento
-- Decremento
Na linha {2}, temos os operadores de atribuição. Na tabela a seguir,
apresentamos os operadores e suas descrições:
Operador de
atribuição
Descrição
= Atribuição
+= Atribuição de soma (x += y) == (x = x + y)
-= Atribuição de subtração (x -= y) == (x = x – y)
*=
Atribuição de multiplicação (x *= y) == (x = x *
y)
/= Atribuição de divisão (x /= y) == (x = x / y)
%= Atribuição de resto (x %= y) == (x = x % y)
Na linha {3}, temos os operadores de comparação. Na tabela a seguir,
apresentamos os operadores e suas descrições:
Operador de
comparação
Descrição
== Igual a
===
Igual a (tanto o valor quanto o tipo do
objeto)
!= Diferente de
> Maior que
>= Maior ou igual a
< Menor que
<= Menor ou igual a
Por fim, na linha {4}, temos os operadores lógicos. Na tabela a seguir,
apresentamos os operadores e suas descrições:
Operador
lógico
Descriçã
o
&& E
|| Ou
! Negação
40. that long ago you had left this part of the world forever."
Mendoza shook his head slowly, and was lost in reverie. At last he
spoke. "My heart overflows with rejoicing at this privilege of hearing your
voice once more, and of taking your hand in mine. Time touches you
lightly, Romalda."
"And you, also, my Don José, of the erect shoulders and stalwart form."
There under the arbor, with the busy life of the Mission going on about
them, they talked until the long shades came.
It was not until Padre Osuna stood by their side and said, "Madre mia,
the twilight must chill thee after the warmth of Rajput," that they parted.
Matronas attended the mother, while the friar conducted Mendoza to the
lodge gate.
"Señor," he said, "I have advised my brethren to resist secularization by
every means within their power. Were it possible for me to remain as head
of this Mission I would fight, to the last, the proposed encroachment."
The neighboring hacenderos vied among themselves to do honor to the
Princess do Castello Branco, guest of the province. The days came and went
in delightful companionship.
Finally, the time for the homeward journey had arrived. The British ship
was sailing out of San Francisco harbor, on the afternoon tide.
Lady Romalda and Señor Mendoza were standing on the forward deck,
looking out over the vast, restless sea. She was talking rapidly. He spoke
little.
The vessel began pitching on the swells that precede the bar.
It was the moment of parting.
They stood, hands clasped. The lady's eyes were streaming. The
Administrator's good-by broke in his voice.
41. A boat was lowered over the side, and Señor Mendoza was rowed to the
fort.
The ship gathered headway, crossed the bar, and lost itself in the horizon
of the ocean.
CHAPTER XXXII
A WEDDING
Merrily rang the chimes in the old belfry of the Mission church of San
José de Guadalupe. "Come! Come! Come! Come, Come!" the call sounded
far out into the valley shimmering in the green of springtide.
"Come! Come! Come! Come, Come!" echoed the hills.
Pigeons, denizens of the church tower, flew in, and out, and around, the
whirring of their wings sounding above the resonance of the bells, in the
intervals of their summoning notes. Flocks darted into the air, circled for a
moment, then disappeared, as if bearing away urgent messages. Others
dropped from emptiness, clung to the gargoyles on the belfry corners, and,
in low cooings, told some story.
"We are coming! coming! coming!" came in refrain from many
footbeats. Men and women from throughout the entire province were
gathering on the eastern slope of Santa Clara Valley that bright spring
morning.
The Vallejos, of the North, came; their ladies were there, and their sons
and their daughters, personifications of the intellect, the valor, the virtue
and the beauty which glorified the valley of the Moon. Gold and silver
bespangled their horses' bridles, hung as pendants from the bridlereins,
inlaid the stirrups, and gilded the saddles from high pommel in the front to
long anquera reaching back to crupper.
42. Gold lace adorned the hatbands and decorated the ponchos of the men,
while gold spurs clicked at their heels. Silk and satin embellished señoritas
beautiful and señoras handsome. Peons and peonas, jigging after their
masters on horses clean-limbed and swift, were bravely attired as for a
fiesta.
The Picos rode in from the South, with retinue as splendid as that of their
Sonoma rivals, their Gallic heritage showing in the harmony and
luxuriousness of color in poncho and gowning.
José Antonio Carillo escorted representatives of his family along the
Camino Real, through San José pueblo, on to San José Mission, four
leagues away toward the setting sun.
The Bandinis followed the de la Guerras. The Auguellos and the
Malarins paced side by side. The busy bee of politics buzzed in vain in the
cap of Juan de Bautista Alvarado, for the active brain beneath was under the
spell of superior attraction in Mission San José, and the man hastened
thither faster than if the governor's chair awaited him there.
Señor Castro, the steadfast, flanked his friend Señor Alvarado, and
looked about complacently, contentment complete, since his equipment
equaled any present.
The "Bostons," allied to the Spanish families, were there, as Latin in
dress and manner as the Spaniards themselves.
"Come! Come! Come, Come!" the bell kept saying. "Come, to the
nuptials of the Señorita Carmelita Mendoza and the Señor Alfredo
Morando."
Mission San José lay nestling in verdure. The vineyards pointed their
budding tendrils low, their gentler tints soft against the darker leaves of the
olive groves.
Orange orchards rioted in magnificence on the sunny slopes. The tree
foliage, shot through with the waxy petals of next year's promise, half hid
the golden balls of this year's harvest still awaiting the gathering hand.
43. Almond trees, as yet showing never a leaf, were beclouded by their
snowy flowerings into vast pillars.
Gentle breezes rose and fell. Soft blossom-showers whitened the ground,
eddied around parent tree-trunk, or crept to modest hiding place amidst the
grass-blades.
Everywhere the odor of growing things loaded the air with sweet
messages. Myriad flower-breaths floated through open doors and windows,
dropping fragrant tribute in hacienda house and cloistered corridor.
People in throngs, eager with expectancy, held the street fronting on the
Mendoza hacienda house. Masters of ceremony opened a wide lane from
mansion to church. The Spanish gentry fringed either side; detachments of
soldiers, in serried rank, stood next; back of them, overflowing to the very
limits of the village, crowded other residents of the valley.
The deep-throated organ within the church began to voice its
monologue. The conversation of hidalgos fell to whisper; the chatter of
peons and peonas hushed.
The great gate of the courtyard swung open wide. Through the archway,
on a palfrey white as milk, came the daughter of the de la Mendoza. Her
mount, true to the strain of his forebears in far-away Arabia, caracoled to
and fro, and ambled forward slowly, step by step, as if to show the
perfection that California could breed in priceless horseflesh. His mane
flowed into the trappings on his breast; his streaming tail almost touched
the ground.
Carmelita, gowned in white, rode stately, as became the princess that she
well might be. The wreath of orange bloom clinging above her forehead
would have made a fitting diadem. The folds of her bridal robe fell
entrancingly about her. With eyes cast down, cheeks aglow, she passed
along, the fairest bride Santa Clara Valley ever saw; no small claim, indeed,
for hers was a time and she of a race wherefrom beautiful women sprang in
plenty.
44. Here bridesmaids followed in double file, their horses white, every one;
their apparel, the delicate pink of the first flush of dawn, the result of
skillful needlewomen through many a day.
Lolita Hernandez, pretty and piquant, was side by side with Lucinda
Higuera, demure and handsome. Alfreda Castro, with raven hair showing
beneath her satin head-covering, moved along with Tula Laynez, gray-eyed,
blonde-cheeked, and saucy as a sparrow. Palmita Peralta, with cherry lips
ever smiling, was paired with Leopolda Estudillo, of the starry eyes.
The bride has reached the church steps.
Deftly her feet disengage themselves from the silken loops used for
stirrup; nimbly she reaches ground. Quickly the following señoritas are at
her side, while peon grooms lead away the horses.
"Viva! Viva! The Señorita Mendoza! Viva! Viva!"
Then from some one: "Viva! the Señorita doña's bridesmaids!"
"Ah! Ah! Look!" cried many.
Morando, on coal-black steed, came through the gate and slowly to the
church door. Comandante of all California he was now, promotion from
guardian of pueblo San José to post commander at Yerba Buena having
been succeeded by transfer to Monterey presidio; and, finally, came the
command of all the land forces.
With him rode, as groomsmen, the presidio commanders of Yerba
Buena, of Monterey, of Santa Barbara, and of San Diego, and accompanied
by many caballeros.
Señor Mendoza, now Governor Mendoza, was horsed on old Mercurio
falling into years, still peerless for speed in all the valley. Flanked by
members of his council and the junta departmental the Governor made his
way up to the church. With sweeping gesture of his bridle-rein, to the right
and to the left, he gave salute for salute to the waiting grandees, as he
passed along.
45. Up the aisle, decorated with innumerable Castilian roses intertwined
with ivy, came Carmelita, on her father's arm, orange blossoms clustered in
her hand, her bridesmaids well in the lead.
The organ swelled in notes of rejoicing.
Directly before the señorita went two little girls, clad in white, backing
slowly altarward, as she advanced. Freshly gathered rose-petals, handful by
handful, they showered before her, making a pathway sweetly yielding as
she trod.
Captain Morando, awaiting his bride, stood at the altar gate, in uniform,
his poncho laid aside, his brother officers attending him.
Bride and groom knelt within the sanctuary.
Neophyte Indian acolytes swung censers. Incense hung in the air,
tingling the nostrils with its Oriental perfume, while the many candles
glowed through the maze like burnished spear-points.
As the clergy solemnly intoned the nuptial service, the choir, a hundred
strong, of Indian men and women touchingly gave back its responses. The
melody of Pepita's voice flooded nave and chancel, love for her mistress the
inspiration.
An instant's pause. Every breath stilled.
With hands upraised over bride and groom stood the officiating padre.
"Whom, therefore, God hath joined together let no man put asunder."
Down the aisle husband and wife led bridesmaid and groomsman,
governor, council, and junta departmental.
Muskets crashed, as they crossed the street; the multitude shouted
congratulations; the hills above them lived in medley of reiterated
acclaimings of good will.
At the wedding breakfast words dripped like honey from the mouth of
Señor Alvarado, as he spoke of the lovely bride. Grave Castro smiled
46. approbation; the clever Carillo applauded; his ally, Don Pio Pico, cried
aloud, "Bon! Bon! Buena!" Even Alvarado's saturnine enemy, the half-
Sicilian, Di Vestro, clapped his hands, as the señor, the honey-drip
becoming torrential eloquence, said: "For the kiss of such a bride as the
Señora Morando, gladly would I again drive that Mexican usurper,
Micheltorena, from California soil; yes, and every follower he has!"
"Will you! Will you!" exclaimed the young wife, blushing at mention of
the new name. Stepping up, she kissed squarely the Señor Alvarado, her
mother's brother.
"A challenge! A challenge!" from the guests. "The former governor at
last has found a nut he cannot crack. Aha! Alvarado, thy kinswoman is ever
quicker in retort than thou."
The tall politician bowed gently to the Señora Doña Carmelita.
"If you draw them hither, mi querida, no power of mine could budge
them a single inch."
"Well said! Well said!"
Later came the afternoon barbecue in the foothills. Dozens of beeves
were roasting in deep pits, on live-coals, the outdoor sports of early
California first whetting the appetite for the feast.
Bonfire blazed red against crag and forest that night, as peon and peona
continued the repast, and danced the fandango to the music of guitar, and
the surprised cries of catamount and wolf.
At the hacienda house the Señor and Señora Morando danced in the
contra danza amidst the plaudits of the lookers-on.
Señor Mendoza, threescore and ten and one, led forth the lithe Francesca
Sanchez, and never youth tripped a lighter step than did the governor of
California at his daughter's wedding.
47. Pio Pico, gallant and graceful, placed his hat on a señorita's head, and
they followed Mendoza and his partner.
Alvarado and Castro, Pedro Zelaya and Abelardo Peralta found ladies
and joined; so did de la Barra, and Higuera, Salvador Vallejo and Nazario
Dominguez, until, as some said, California north, and south, and center, was
united, if only for the contra danza.
Small hours found the gaiety undiminished, for midnight supper
strengthened for further dancing. Neither was one day deemed sufficient to
do adequate honor to the marriage of Carmelita Mendoza and Comandante
Morando.
Next day the couple, the Governor Mendoza, and all friends repaired to
the hacienda house of Fulgencio Higuera, two leagues away, to dance and
to make merry till the break of another morning.
The third day was passed with Señor Berryessa, near pueblo San José,
the following at Marco Calderon's, and so on.
The seventh day found them entering the porte cochere of their own
home, once the residence of Colonel Barcelo, from whose gates, ere many
moons, they were to see, with rejoicing hearts, the Stars and Stripes burst,
in unending vigil, over government house, plaza and castle.
Long years, and happy ones, they lived, and their descendants, now of
the third and fourth generation, bless their memory, and tell of the honor,
the bravery, the virtue of General Morando and his bride of Mission San
José.
48. *** END OF THE PROJECT GUTENBERG EBOOK THE BRIDE OF
MISSION SAN JOSÉ: A TALE OF EARLY CALIFORNIA ***
Updated editions will replace the previous one—the old editions will
be renamed.
Creating the works from print editions not protected by U.S.
copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.
START: FULL LICENSE
50. PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK
To protect the Project Gutenberg™ mission of promoting the free
distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.
Section 1. General Terms of Use and
Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.
1.B. “Project Gutenberg” is a registered trademark. It may only be
used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
51. 1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.
1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.
1.E. Unless you have removed all references to Project Gutenberg:
1.E.1. The following sentence, with active links to, or other
immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
52. This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
1.E.2. If an individual Project Gutenberg™ electronic work is derived
from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.
1.E.3. If an individual Project Gutenberg™ electronic work is posted
with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.
1.E.4. Do not unlink or detach or remove the full Project
Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.
1.E.5. Do not copy, display, perform, distribute or redistribute this
electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
53. with active links or immediate access to the full terms of the Project
Gutenberg™ License.
1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.
1.E.7. Do not charge a fee for access to, viewing, displaying,
performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.
1.E.8. You may charge a reasonable fee for copies of or providing
access to or distributing Project Gutenberg™ electronic works
provided that:
• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
54. about donations to the Project Gutenberg Literary Archive
Foundation.”
• You provide a full refund of any money paid by a user who
notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.
• You provide, in accordance with paragraph 1.F.3, a full refund of
any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.
• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.
1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™
electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.
1.F.
1.F.1. Project Gutenberg volunteers and employees expend
considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
55. damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.
1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for
the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.
1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you
discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.
1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
56. INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.
1.F.5. Some states do not allow disclaimers of certain implied
warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.
1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,
the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.
Section 2. Information about the Mission
of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.
Volunteers and financial support to provide volunteers with the
assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
57. remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.
Section 3. Information about the Project
Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.
The Foundation’s business office is located at 809 North 1500 West,
Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact
Section 4. Information about Donations to
the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
58. small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.
The Foundation is committed to complying with the laws regulating
charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.
While we cannot and do not solicit contributions from states where
we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.
International donations are gratefully accepted, but we cannot make
any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.
Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.
Section 5. General Information About
Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
59. Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.
Most people start at our website which has the main PG search
facility: www.gutenberg.org.
This website includes information about Project Gutenberg™,
including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.