From 639a74061e2eaadbbb01c9afc71712b9968e8322 Mon Sep 17 00:00:00 2001 From: Gabriel Fernandes Silva Date: Fri, 12 Dec 2025 22:48:25 -0300 Subject: [PATCH 1/3] Translate comments and test descriptions to Portuguese in the concat function implementation. --- .../01-concat/_js.view/solution.js | 8 ++++---- .../01-concat/_js.view/source.js | 2 +- .../01-concat/_js.view/test.js | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/solution.js b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/solution.js index 00c37bb94..223c878d9 100644 --- a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/solution.js +++ b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/solution.js @@ -1,13 +1,13 @@ function concat(arrays) { - // sum of individual array lengths + // soma dos comprimentos individuais dos arrays let totalLength = arrays.reduce((acc, value) => acc + value.length, 0); let result = new Uint8Array(totalLength); - + if (!arrays.length) return result; - // for each array - copy it over result - // next array is copied right after the previous one + // para cada array - copie-o sobre o resultado + // O próximo array é copiado imediatamente após o anterior. let length = 0; for(let array of arrays) { result.set(array, length); diff --git a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/source.js b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/source.js index e88b1a537..03614477f 100644 --- a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/source.js +++ b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/source.js @@ -1,5 +1,5 @@ function concat(arrays) { - // ...your code... + // ...seu código... } let chunks = [ diff --git a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/test.js b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/test.js index bcb19daef..a1f3d2828 100644 --- a/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/test.js +++ b/4-binary/01-arraybuffer-binary-arrays/01-concat/_js.view/test.js @@ -5,14 +5,14 @@ describe("concat", function() { new Uint8Array([6, 7, 8]) ]; - it("result has the same array type", function() { + it("resultado possui o mesmo tipo de array", function() { let result = concat(chunks); assert.equal(result.constructor, Uint8Array); }); - it("concatenates arrays", function() { + it("concatena arrays", function() { let result = concat(chunks); @@ -20,7 +20,7 @@ describe("concat", function() { }); - it("returns empty array on empty input", function() { + it("Retorna um array vazio se a entrada estiver vazia.", function() { let result = concat([]); From ad3b63c9144a3be36767bcfead023f6d6efd469f Mon Sep 17 00:00:00 2001 From: Gabriel Fernandes Silva Date: Fri, 12 Dec 2025 22:48:40 -0300 Subject: [PATCH 2/3] Translate task description to Portuguese in the concat function documentation. --- 4-binary/01-arraybuffer-binary-arrays/01-concat/task.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/4-binary/01-arraybuffer-binary-arrays/01-concat/task.md b/4-binary/01-arraybuffer-binary-arrays/01-concat/task.md index 6710104b2..13a198019 100644 --- a/4-binary/01-arraybuffer-binary-arrays/01-concat/task.md +++ b/4-binary/01-arraybuffer-binary-arrays/01-concat/task.md @@ -1,4 +1,4 @@ -# Concatenate typed arrays +# Concatenar arrays tipados -Given an array of `Uint8Array`, write a function `concat(arrays)` that returns a concatenation of them into a single array. +Dado um array de `Uint8Array`, escreva uma função `concat(arrays)` que retorna uma concatenação deles em um único array. From 0170f486b6aedcef86f1962d29b755eba2f893e6 Mon Sep 17 00:00:00 2001 From: Gabriel Fernandes Silva Date: Sat, 13 Dec 2025 23:17:22 -0300 Subject: [PATCH 3/3] Translate article on ArrayBuffer and binary arrays to Portuguese. --- .../01-arraybuffer-binary-arrays/article.md | 234 +++++++++--------- 1 file changed, 117 insertions(+), 117 deletions(-) diff --git a/4-binary/01-arraybuffer-binary-arrays/article.md b/4-binary/01-arraybuffer-binary-arrays/article.md index 2827e277e..9cbe8e053 100644 --- a/4-binary/01-arraybuffer-binary-arrays/article.md +++ b/4-binary/01-arraybuffer-binary-arrays/article.md @@ -1,87 +1,87 @@ -# ArrayBuffer, binary arrays +# ArrayBuffer, arrays binários -In web-development we meet binary data mostly while dealing with files (create, upload, download). Another typical use case is image processing. +No desenvolvimento web encontramos dados binários principalmente ao lidar com arquivos (criar, enviar, baixar). Outro caso de uso típico é o processamento de imagens. -That's all possible in JavaScript, and binary operations are high-performant. +Tudo isso é possível em JavaScript, e as operações binárias são de alto desempenho. -Although, there's a bit of confusion, because there are many classes. To name a few: +No entanto, há um pouco de confusão, porque existem muitas classes. Para citar algumas: - `ArrayBuffer`, `Uint8Array`, `DataView`, `Blob`, `File`, etc. -Binary data in JavaScript is implemented in a non-standard way, compared to other languages. But when we sort things out, everything becomes fairly simple. +Os dados binários em JavaScript são implementados de uma forma não padrão, comparado a outras linguagens. Mas quando organizamos as coisas, tudo se torna bastante simples. -**The basic binary object is `ArrayBuffer` -- a reference to a fixed-length contiguous memory area.** +**O objeto binário básico é `ArrayBuffer` -- uma referência a uma área de memória contígua de comprimento fixo.** -We create it like this: +Criamos assim: ```js run -let buffer = new ArrayBuffer(16); // create a buffer of length 16 +let buffer = new ArrayBuffer(16); // cria um buffer de comprimento 16 alert(buffer.byteLength); // 16 ``` -This allocates a contiguous memory area of 16 bytes and pre-fills it with zeroes. +Isso aloca uma área de memória contígua de 16 bytes e a preenche com zeros. -```warn header="`ArrayBuffer` is not an array of something" -Let's eliminate a possible source of confusion. `ArrayBuffer` has nothing in common with `Array`: -- It has a fixed length, we can't increase or decrease it. -- It takes exactly that much space in the memory. -- To access individual bytes, another "view" object is needed, not `buffer[index]`. +```warn header="`ArrayBuffer` não é um array de algo" +Vamos eliminar uma possível fonte de confusão. `ArrayBuffer` não tem nada em comum com `Array`: +- Tem um comprimento fixo, não podemos aumentá-lo ou diminuí-lo. +- Ocupa exatamente esse espaço na memória. +- Para acessar bytes individuais, é necessário outro objeto "view", não `buffer[index]`. ``` -`ArrayBuffer` is a memory area. What's stored in it? It has no clue. Just a raw sequence of bytes. +`ArrayBuffer` é uma área de memória. O que está armazenado nela? Não tem ideia. Apenas uma sequência bruta de bytes. -**To manipulate an `ArrayBuffer`, we need to use a "view" object.** +**Para manipular um `ArrayBuffer`, precisamos usar um objeto "view".** -A view object does not store anything on its own. It's the "eyeglasses" that give an interpretation of the bytes stored in the `ArrayBuffer`. +Um objeto view não armazena nada por si só. São os "óculos" que dão uma interpretação dos bytes armazenados no `ArrayBuffer`. -For instance: +Por exemplo: -- **`Uint8Array`** -- treats each byte in `ArrayBuffer` as a separate number, with possible values from 0 to 255 (a byte is 8-bit, so it can hold only that much). Such value is called a "8-bit unsigned integer". -- **`Uint16Array`** -- treats every 2 bytes as an integer, with possible values from 0 to 65535. That's called a "16-bit unsigned integer". -- **`Uint32Array`** -- treats every 4 bytes as an integer, with possible values from 0 to 4294967295. That's called a "32-bit unsigned integer". -- **`Float64Array`** -- treats every 8 bytes as a floating point number with possible values from 5.0x10-324 to 1.8x10308. +- **`Uint8Array`** -- trata cada byte no `ArrayBuffer` como um número separado, com valores possíveis de 0 a 255 (um byte tem 8 bits, então só pode conter isso). Esse valor é chamado de "inteiro sem sinal de 8 bits". +- **`Uint16Array`** -- trata cada 2 bytes como um inteiro, com valores possíveis de 0 a 65535. Isso é chamado de "inteiro sem sinal de 16 bits". +- **`Uint32Array`** -- trata cada 4 bytes como um inteiro, com valores possíveis de 0 a 4294967295. Isso é chamado de "inteiro sem sinal de 32 bits". +- **`Float64Array`** -- trata cada 8 bytes como um número de ponto flutuante com valores possíveis de 5.0x10-324 a 1.8x10308. -So, the binary data in an `ArrayBuffer` of 16 bytes can be interpreted as 16 "tiny numbers", or 8 bigger numbers (2 bytes each), or 4 even bigger (4 bytes each), or 2 floating-point values with high precision (8 bytes each). +Assim, os dados binários em um `ArrayBuffer` de 16 bytes podem ser interpretados como 16 "números pequenos", ou 8 números maiores (2 bytes cada), ou 4 ainda maiores (4 bytes cada), ou 2 valores de ponto flutuante com alta precisão (8 bytes cada). ![](arraybuffer-views.svg) -`ArrayBuffer` is the core object, the root of everything, the raw binary data. +`ArrayBuffer` é o objeto central, a raiz de tudo, os dados binários brutos. -But if we're going to write into it, or iterate over it, basically for almost any operation – we must use a view, e.g: +Mas se vamos escrever nele, ou iterar sobre ele, basicamente para quase qualquer operação – devemos usar uma view, por exemplo: ```js run -let buffer = new ArrayBuffer(16); // create a buffer of length 16 +let buffer = new ArrayBuffer(16); // cria um buffer de comprimento 16 *!* -let view = new Uint32Array(buffer); // treat buffer as a sequence of 32-bit integers +let view = new Uint32Array(buffer); // trata o buffer como uma sequência de inteiros de 32 bits -alert(Uint32Array.BYTES_PER_ELEMENT); // 4 bytes per integer +alert(Uint32Array.BYTES_PER_ELEMENT); // 4 bytes por inteiro */!* -alert(view.length); // 4, it stores that many integers -alert(view.byteLength); // 16, the size in bytes +alert(view.length); // 4, armazena essa quantidade de inteiros +alert(view.byteLength); // 16, o tamanho em bytes -// let's write a value +// vamos escrever um valor view[0] = 123456; -// iterate over values +// iterar sobre os valores for(let num of view) { - alert(num); // 123456, then 0, 0, 0 (4 values total) + alert(num); // 123456, depois 0, 0, 0 (4 valores no total) } ``` ## TypedArray -The common term for all these views (`Uint8Array`, `Uint32Array`, etc) is [TypedArray](https://tc39.github.io/ecma262/#sec-typedarray-objects). They share the same set of methods and properties. +O termo comum para todas essas views (`Uint8Array`, `Uint32Array`, etc) é [TypedArray](https://tc39.github.io/ecma262/#sec-typedarray-objects). Elas compartilham o mesmo conjunto de métodos e propriedades. -Please note, there's no constructor called `TypedArray`, it's just a common "umbrella" term to represent one of views over `ArrayBuffer`: `Int8Array`, `Uint8Array` and so on, the full list will soon follow. +Note que não há um construtor chamado `TypedArray`, é apenas um termo comum "guarda-chuva" para representar uma das views sobre `ArrayBuffer`: `Int8Array`, `Uint8Array` e assim por diante, a lista completa virá em breve. -When you see something like `new TypedArray`, it means any of `new Int8Array`, `new Uint8Array`, etc. +Quando você vê algo como `new TypedArray`, significa qualquer um de `new Int8Array`, `new Uint8Array`, etc. -Typed arrays behave like regular arrays: have indexes and are iterable. +Arrays tipados se comportam como arrays regulares: têm índices e são iteráveis. -A typed array constructor (be it `Int8Array` or `Float64Array`, doesn't matter) behaves differently depending on argument types. +Um construtor de array tipado (seja `Int8Array` ou `Float64Array`, não importa) se comporta de forma diferente dependendo dos tipos de argumentos. -There are 5 variants of arguments: +Existem 5 variantes de argumentos: ```js new TypedArray(buffer, [byteOffset], [length]); @@ -91,92 +91,92 @@ new TypedArray(length); new TypedArray(); ``` -1. If an `ArrayBuffer` argument is supplied, the view is created over it. We used that syntax already. +1. Se um argumento `ArrayBuffer` for fornecido, a view é criada sobre ele. Já usamos essa sintaxe. - Optionally we can provide `byteOffset` to start from (0 by default) and the `length` (till the end of the buffer by default), then the view will cover only a part of the `buffer`. + Opcionalmente podemos fornecer `byteOffset` para começar (0 por padrão) e o `length` (até o fim do buffer por padrão), então a view cobrirá apenas uma parte do `buffer`. -2. If an `Array`, or any array-like object is given, it creates a typed array of the same length and copies the content. +2. Se um `Array`, ou qualquer objeto semelhante a array for fornecido, cria um array tipado do mesmo comprimento e copia o conteúdo. - We can use it to pre-fill the array with the data: + Podemos usá-lo para pré-preencher o array com os dados: ```js run *!* let arr = new Uint8Array([0, 1, 2, 3]); */!* - alert( arr.length ); // 4, created binary array of the same length - alert( arr[1] ); // 1, filled with 4 bytes (unsigned 8-bit integers) with given values + alert( arr.length ); // 4, criou array binário do mesmo comprimento + alert( arr[1] ); // 1, preenchido com 4 bytes (inteiros sem sinal de 8 bits) com os valores dados ``` -3. If another `TypedArray` is supplied, it does the same: creates a typed array of the same length and copies values. Values are converted to the new type in the process, if needed. +3. Se outro `TypedArray` for fornecido, faz o mesmo: cria um array tipado do mesmo comprimento e copia os valores. Os valores são convertidos para o novo tipo no processo, se necessário. ```js run let arr16 = new Uint16Array([1, 1000]); *!* let arr8 = new Uint8Array(arr16); */!* alert( arr8[0] ); // 1 - alert( arr8[1] ); // 232, tried to copy 1000, but can't fit 1000 into 8 bits (explanations below) + alert( arr8[1] ); // 232, tentou copiar 1000, mas não consegue encaixar 1000 em 8 bits (explicações abaixo) ``` -4. For a numeric argument `length` -- creates the typed array to contain that many elements. Its byte length will be `length` multiplied by the number of bytes in a single item `TypedArray.BYTES_PER_ELEMENT`: +4. Para um argumento numérico `length` -- cria o array tipado para conter essa quantidade de elementos. Seu comprimento em bytes será `length` multiplicado pelo número de bytes em um único item `TypedArray.BYTES_PER_ELEMENT`: ```js run - let arr = new Uint16Array(4); // create typed array for 4 integers - alert( Uint16Array.BYTES_PER_ELEMENT ); // 2 bytes per integer - alert( arr.byteLength ); // 8 (size in bytes) + let arr = new Uint16Array(4); // cria array tipado para 4 inteiros + alert( Uint16Array.BYTES_PER_ELEMENT ); // 2 bytes por inteiro + alert( arr.byteLength ); // 8 (tamanho em bytes) ``` -5. Without arguments, creates an zero-length typed array. +5. Sem argumentos, cria um array tipado de comprimento zero. -We can create a `TypedArray` directly, without mentioning `ArrayBuffer`. But a view cannot exist without an underlying `ArrayBuffer`, so gets created automatically in all these cases except the first one (when provided). +Podemos criar um `TypedArray` diretamente, sem mencionar `ArrayBuffer`. Mas uma view não pode existir sem um `ArrayBuffer` subjacente, então é criado automaticamente em todos esses casos, exceto no primeiro (quando fornecido). -To access the underlying `ArrayBuffer`, there are following properties in `TypedArray`: -- `buffer` -- references the `ArrayBuffer`. -- `byteLength` -- the length of the `ArrayBuffer`. +Para acessar o `ArrayBuffer` subjacente, existem as seguintes propriedades em `TypedArray`: +- `buffer` -- referencia o `ArrayBuffer`. +- `byteLength` -- o comprimento do `ArrayBuffer`. -So, we can always move from one view to another: +Assim, sempre podemos passar de uma view para outra: ```js let arr8 = new Uint8Array([0, 1, 2, 3]); -// another view on the same data +// outra view sobre os mesmos dados let arr16 = new Uint16Array(arr8.buffer); ``` -Here's the list of typed arrays: +Aqui está a lista de arrays tipados: -- `Uint8Array`, `Uint16Array`, `Uint32Array` -- for integer numbers of 8, 16 and 32 bits. - - `Uint8ClampedArray` -- for 8-bit integers, "clamps" them on assignment (see below). -- `Int8Array`, `Int16Array`, `Int32Array` -- for signed integer numbers (can be negative). -- `Float32Array`, `Float64Array` -- for signed floating-point numbers of 32 and 64 bits. +- `Uint8Array`, `Uint16Array`, `Uint32Array` -- para números inteiros de 8, 16 e 32 bits. + - `Uint8ClampedArray` -- para inteiros de 8 bits, os "limita" na atribuição (veja abaixo). +- `Int8Array`, `Int16Array`, `Int32Array` -- para números inteiros com sinal (podem ser negativos). +- `Float32Array`, `Float64Array` -- para números de ponto flutuante com sinal de 32 e 64 bits. -```warn header="No `int8` or similar single-valued types" -Please note, despite of the names like `Int8Array`, there's no single-value type like `int`, or `int8` in JavaScript. +```warn header="Sem `int8` ou tipos de valor único similares" +Note que, apesar dos nomes como `Int8Array`, não existe um tipo de valor único como `int`, ou `int8` em JavaScript. -That's logical, as `Int8Array` is not an array of these individual values, but rather a view on `ArrayBuffer`. +Isso é lógico, pois `Int8Array` não é um array desses valores individuais, mas sim uma view sobre `ArrayBuffer`. ``` -### Out-of-bounds behavior +### Comportamento fora dos limites -What if we attempt to write an out-of-bounds value into a typed array? There will be no error. But extra bits are cut-off. +E se tentarmos escrever um valor fora dos limites em um array tipado? Não haverá erro. Mas os bits extras são cortados. -For instance, let's try to put 256 into `Uint8Array`. In binary form, 256 is `100000000` (9 bits), but `Uint8Array` only provides 8 bits per value, that makes the available range from 0 to 255. +Por exemplo, vamos tentar colocar 256 em `Uint8Array`. Na forma binária, 256 é `100000000` (9 bits), mas `Uint8Array` fornece apenas 8 bits por valor, o que torna o intervalo disponível de 0 a 255. -For bigger numbers, only the rightmost (less significant) 8 bits are stored, and the rest is cut off: +Para números maiores, apenas os 8 bits mais à direita (menos significativos) são armazenados, e o resto é cortado: ![](8bit-integer-256.svg) -So we'll get zero. +Então obteremos zero. -For 257, the binary form is `100000001` (9 bits), the rightmost 8 get stored, so we'll have `1` in the array: +Para 257, a forma binária é `100000001` (9 bits), os 8 mais à direita são armazenados, então teremos `1` no array: ![](8bit-integer-257.svg) -In other words, the number modulo 28 is saved. +Em outras palavras, o número módulo 28 é salvo. -Here's the demo: +Aqui está a demonstração: ```js run let uint8array = new Uint8Array(16); let num = 256; -alert(num.toString(2)); // 100000000 (binary representation) +alert(num.toString(2)); // 100000000 (representação binária) uint8array[0] = 256; uint8array[1] = 257; @@ -185,88 +185,88 @@ alert(uint8array[0]); // 0 alert(uint8array[1]); // 1 ``` -`Uint8ClampedArray` is special in this aspect, its behavior is different. It saves 255 for any number that is greater than 255, and 0 for any negative number. That behavior is useful for image processing. +`Uint8ClampedArray` é especial nesse aspecto, seu comportamento é diferente. Salva 255 para qualquer número maior que 255, e 0 para qualquer número negativo. Esse comportamento é útil para processamento de imagens. -## TypedArray methods +## Métodos TypedArray -`TypedArray` has regular `Array` methods, with notable exceptions. +`TypedArray` tem métodos regulares de `Array`, com exceções notáveis. -We can iterate, `map`, `slice`, `find`, `reduce` etc. +Podemos iterar, `map`, `slice`, `find`, `reduce` etc. -There are few things we can't do though: +Há algumas coisas que não podemos fazer: -- No `splice` -- we can't "delete" a value, because typed arrays are views on a buffer, and these are fixed, contiguous areas of memory. All we can do is to assign a zero. -- No `concat` method. +- Sem `splice` -- não podemos "deletar" um valor, porque arrays tipados são views sobre um buffer, e essas são áreas fixas e contíguas de memória. Tudo que podemos fazer é atribuir um zero. +- Sem método `concat`. -There are two additional methods: +Existem dois métodos adicionais: -- `arr.set(fromArr, [offset])` copies all elements from `fromArr` to the `arr`, starting at position `offset` (0 by default). -- `arr.subarray([begin, end])` creates a new view of the same type from `begin` to `end` (exclusive). That's similar to `slice` method (that's also supported), but doesn't copy anything -- just creates a new view, to operate on the given piece of data. +- `arr.set(fromArr, [offset])` copia todos os elementos de `fromArr` para `arr`, começando na posição `offset` (0 por padrão). +- `arr.subarray([begin, end])` cria uma nova view do mesmo tipo de `begin` a `end` (exclusivo). Isso é semelhante ao método `slice` (que também é suportado), mas não copia nada -- apenas cria uma nova view, para operar no pedaço de dados dado. -These methods allow us to copy typed arrays, mix them, create new arrays from existing ones, and so on. +Esses métodos nos permitem copiar arrays tipados, misturá-los, criar novos arrays a partir dos existentes, e assim por diante. ## DataView -[DataView](mdn:/JavaScript/Reference/Global_Objects/DataView) is a special super-flexible "untyped" view over `ArrayBuffer`. It allows to access the data on any offset in any format. +[DataView](mdn:/JavaScript/Reference/Global_Objects/DataView) é uma view especial superflexível "não tipada" sobre `ArrayBuffer`. Permite acessar os dados em qualquer deslocamento em qualquer formato. -- For typed arrays, the constructor dictates what the format is. The whole array is supposed to be uniform. The i-th number is `arr[i]`. -- With `DataView` we access the data with methods like `.getUint8(i)` or `.getUint16(i)`. We choose the format at method call time instead of the construction time. +- Para arrays tipados, o construtor dita qual é o formato. Todo o array deve ser uniforme. O i-ésimo número é `arr[i]`. +- Com `DataView` acessamos os dados com métodos como `.getUint8(i)` ou `.getUint16(i)`. Escolhemos o formato no momento da chamada do método, em vez do momento da construção. -The syntax: +A sintaxe: ```js new DataView(buffer, [byteOffset], [byteLength]) ``` -- **`buffer`** -- the underlying `ArrayBuffer`. Unlike typed arrays, `DataView` doesn't create a buffer on its own. We need to have it ready. -- **`byteOffset`** -- the starting byte position of the view (by default 0). -- **`byteLength`** -- the byte length of the view (by default till the end of `buffer`). +- **`buffer`** -- o `ArrayBuffer` subjacente. Diferente dos arrays tipados, `DataView` não cria um buffer por conta própria. Precisamos tê-lo pronto. +- **`byteOffset`** -- a posição de byte inicial da view (0 por padrão). +- **`byteLength`** -- o comprimento em bytes da view (por padrão até o fim de `buffer`). -For instance, here we extract numbers in different formats from the same buffer: +Por exemplo, aqui extraímos números em diferentes formatos do mesmo buffer: ```js run -// binary array of 4 bytes, all have the maximal value 255 +// array binário de 4 bytes, todos têm o valor máximo 255 let buffer = new Uint8Array([255, 255, 255, 255]).buffer; let dataView = new DataView(buffer); -// get 8-bit number at offset 0 +// obtém número de 8 bits no deslocamento 0 alert( dataView.getUint8(0) ); // 255 -// now get 16-bit number at offset 0, it consists of 2 bytes, together interpreted as 65535 -alert( dataView.getUint16(0) ); // 65535 (biggest 16-bit unsigned int) +// agora obtém número de 16 bits no deslocamento 0, consiste de 2 bytes, juntos interpretados como 65535 +alert( dataView.getUint16(0) ); // 65535 (maior inteiro sem sinal de 16 bits) -// get 32-bit number at offset 0 -alert( dataView.getUint32(0) ); // 4294967295 (biggest 32-bit unsigned int) +// obtém número de 32 bits no deslocamento 0 +alert( dataView.getUint32(0) ); // 4294967295 (maior inteiro sem sinal de 32 bits) -dataView.setUint32(0, 0); // set 4-byte number to zero, thus setting all bytes to 0 +dataView.setUint32(0, 0); // define número de 4 bytes como zero, assim definindo todos os bytes como 0 ``` -`DataView` is great when we store mixed-format data in the same buffer. For example, when we store a sequence of pairs (16-bit integer, 32-bit float), `DataView` allows to access them easily. +`DataView` é ótimo quando armazenamos dados de formato misto no mesmo buffer. Por exemplo, quando armazenamos uma sequência de pares (inteiro de 16 bits, float de 32 bits), `DataView` permite acessá-los facilmente. -## Summary +## Resumo -`ArrayBuffer` is the core object, a reference to the fixed-length contiguous memory area. +`ArrayBuffer` é o objeto central, uma referência à área de memória contígua de comprimento fixo. -To do almost any operation on `ArrayBuffer`, we need a view. +Para fazer quase qualquer operação em `ArrayBuffer`, precisamos de uma view. -- It can be a `TypedArray`: - - `Uint8Array`, `Uint16Array`, `Uint32Array` -- for unsigned integers of 8, 16, and 32 bits. - - `Uint8ClampedArray` -- for 8-bit integers, "clamps" them on assignment. - - `Int8Array`, `Int16Array`, `Int32Array` -- for signed integer numbers (can be negative). - - `Float32Array`, `Float64Array` -- for signed floating-point numbers of 32 and 64 bits. -- Or a `DataView` -- the view that uses methods to specify a format, e.g. `getUint8(offset)`. +- Pode ser um `TypedArray`: + - `Uint8Array`, `Uint16Array`, `Uint32Array` -- para inteiros sem sinal de 8, 16 e 32 bits. + - `Uint8ClampedArray` -- para inteiros de 8 bits, os "limita" na atribuição. + - `Int8Array`, `Int16Array`, `Int32Array` -- para números inteiros com sinal (podem ser negativos). + - `Float32Array`, `Float64Array` -- para números de ponto flutuante com sinal de 32 e 64 bits. +- Ou um `DataView` -- a view que usa métodos para especificar um formato, por exemplo `getUint8(offset)`. -In most cases we create and operate directly on typed arrays, leaving `ArrayBuffer` under cover, as a "common denominator". We can access it as `.buffer` and make another view if needed. +Na maioria dos casos criamos e operamos diretamente em arrays tipados, deixando `ArrayBuffer` sob cobertura, como um "denominador comum". Podemos acessá-lo como `.buffer` e fazer outra view se necessário. -There are also two additional terms, that are used in descriptions of methods that operate on binary data: -- `ArrayBufferView` is an umbrella term for all these kinds of views. -- `BufferSource` is an umbrella term for `ArrayBuffer` or `ArrayBufferView`. +Existem também dois termos adicionais, que são usados em descrições de métodos que operam em dados binários: +- `ArrayBufferView` é um termo guarda-chuva para todos esses tipos de views. +- `BufferSource` é um termo guarda-chuva para `ArrayBuffer` ou `ArrayBufferView`. -We'll see these terms in the next chapters. `BufferSource` is one of the most common terms, as it means "any kind of binary data" -- an `ArrayBuffer` or a view over it. +Veremos esses termos nos próximos capítulos. `BufferSource` é um dos termos mais comuns, pois significa "qualquer tipo de dado binário" -- um `ArrayBuffer` ou uma view sobre ele. -Here's a cheatsheet: +Aqui está uma referência rápida: ![](arraybuffer-view-buffersource.svg)