Skip to content

Commit

Permalink
Content updates (#2038)
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo authored Oct 7, 2023
2 parents 36ba419 + b395b8b commit 1aa4d25
Show file tree
Hide file tree
Showing 11 changed files with 158 additions and 175 deletions.
42 changes: 30 additions & 12 deletions content/redirects.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -1624,12 +1624,6 @@
- from: /js/s/every-nth
to: /js/s/every-nth-element
status: 301!
- from: /js/s/first-n
to: /js/s/first-n-elements
status: 301!
- from: /js/s/last-n
to: /js/s/last-n-elements
status: 301!
- from: /js/s/find-first-n
to: /js/s/find-first-n-matches
status: 301!
Expand All @@ -1642,12 +1636,6 @@
- from: /js/s/min-by
to: /js/s/function-based-array-min
status: 301!
- from: /js/s/max-n
to: /js/s/n-max-elements
status: 301!
- from: /js/s/min-n
to: /js/s/n-min-elements
status: 301!
- from: /js/s/index-of-all
to: /js/s/index-of-all-matches
status: 301!
Expand Down Expand Up @@ -1912,3 +1900,33 @@
- from: /js/s/is-odd
to: /js/s/number-is-even-odd
status: 301!
- from: /js/s/hash-node
to: /js/s/hash-sha-256
status: 301!
- from: /js/s/hash-browser
to: /js/s/hash-sha-256
status: 301!
- from: /js/s/max-n
to: /js/s/n-min-max-elements-in-array
status: 301!
- from: /js/s/min-n
to: /js/s/n-min-max-elements-in-array
status: 301!
- from: /js/s/n-max-elements
to: /js/s/n-min-max-elements-in-array
status: 301!
- from: /js/s/n-min-elements
to: /js/s/n-min-max-elements-in-array
status: 301!
- from: /js/s/first-n
to: /js/s/first-last-n-elements
status: 301!
- from: /js/s/last-n
to: /js/s/first-last-n-elements
status: 301!
- from: /js/s/first-n-elements
to: /js/s/first-last-n-elements
status: 301!
- from: /js/s/last-n-elements
to: /js/s/first-last-n-elements
status: 301!
32 changes: 32 additions & 0 deletions content/snippets/js/s/first-last-n-elements.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
---
title: "Tip: Get the first or last n elements in a JavaScript array"
shortTitle: First or last n elements of an array
type: tip
language: javascript
tags: [array]
author: chalarangelo
cover: fort-lamp
excerpt: Learn how to retrieve the first or last `n` elements in a JavaScript array with a single line of code.
dateModified: 2023-10-04
---

`Array.prototype.slice()` is a versatile tool in every JavaScript developer's arsenal. It retrieves the **values of an array between two indices**, handling edge cases like negative and out-of-bounds indices. This makes it ideal for retrieving the first or last `n` elements of an array.

For the first `n` elements, you can use a start value of `0` and an end value of `n`. For the last `n` elements, you can use a start value of `-n` and no end value.

```js
const firstN = (arr, n = 1) => arr.slice(0, n);
const lastN = (arr, n = 1) => arr.slice(-n);

const arr = ['a', 'b', 'c', 'd'];

firstN(arr); // ['a']
firstN(arr, 2); // ['a', 'b']
firstN(arr, 5); // ['a', 'b', 'c', 'd']

lastN(arr); // ['d']
lastN(arr, 2); // ['c', 'd']
lastN(arr, 5); // ['a', 'b', 'c', 'd']
```

As you can see, it only take a single line of code to get the first or last `n` elements of an array. This code also handles **out-of-bounds indices**, resulting in a shallow clone of the original array. Be mindful of **negative** `n` values, however, as the results will not make much sense.
21 changes: 0 additions & 21 deletions content/snippets/js/s/first-n-elements.md

This file was deleted.

37 changes: 0 additions & 37 deletions content/snippets/js/s/hash-browser.md

This file was deleted.

34 changes: 0 additions & 34 deletions content/snippets/js/s/hash-node.md

This file was deleted.

67 changes: 67 additions & 0 deletions content/snippets/js/s/hash-sha-256.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
---
title: Calculate SHA-256 hash in JavaScript
shortTitle: SHA-256 hash
type: story
language: javascript
tags: [browser,node,promise]
author: chalarangelo
cover: padlocks
excerpt: Calculate a SHA-256 hash in JavaScript using native APIs in both the browser and Node.js.
dateModified: 2023-10-07
---

The [SHA-256](https://en.wikipedia.org/wiki/SHA-2) algorithm is a widely used hash function producing a **256-bit hash value**. It is used in many security applications and protocols, including TLS and SSL, SSH, PGP, and Bitcoin.

Calculating a SHA-256 hash in JavaScript is easy using **native APIs**, but there are some differences between the browser and Node.js. As the browser implementation is asynchronous, both of the examples provided will return a `Promise` for consistency.

### Browser

In the browser, you can use the [SubtleCrypto](https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto) API to create a hash for the given value. You first need to create a new `TextEncoder` and use it to encode the given value. Then, pass its value to `SubtleCrypto.digest()` to generate a digest of the given data, resulting in a `Promise`.

As the promise reslves to an `ArrayBuffer`, you will need to read the data using `DataView.prototype.getUint32()`. Then, you need to convert the data to its hexadecimal representation using `Number.prototype.toString()`. Add the data to an array using `Array.prototype.push()`. Finally, use `Array.prototype.join()` to combine values in the array of `hexes` into a string.

```js
const hashValue = val =>
crypto.subtle
.digest('SHA-256', new TextEncoder('utf-8').encode(val))
.then(h => {
let hexes = [],
view = new DataView(h);
for (let i = 0; i < view.byteLength; i += 4)
hexes.push(('00000000' + view.getUint32(i).toString(16)).slice(-8));
return hexes.join('');
});

hashValue(
JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })
).then(console.log);
// '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
```

### Node.js

In Node.js, you can use the `crypto` module to create a hash for the given value. You first need to create a `Hash` object with the appropriate algorithm using `crypto.createHash()`. Then, use `hash.update()` to add the data from `val` to the `Hash` and `hash.digest()` to calculate the digest of the data.

For consistency with the browser implementation and to prevent blocking on a long operation, we'll return a `Promise` by wrapping it in `setTimeout()`.

```js
import { createHash } from 'crypto';

const hashValue = val =>
new Promise(resolve =>
setTimeout(
() => resolve(createHash('sha256').update(val).digest('hex')),
0
)
);

hashValue(JSON.stringify({ a: 'a', b: [1, 2, 3, 4], foo: { c: 'bar' } })).then(
console.log
);
// '04aa106279f5977f59f9067fa9712afc4aedc6f5862a8defc34552d8c7206393'
```

### Notes

- The two implementations are **not compatible** with each other. You cannot use the browser implementation in Node.js and vice versa.
- Both implementations should produce the same result for the same input.
21 changes: 0 additions & 21 deletions content/snippets/js/s/last-n-elements.md

This file was deleted.

24 changes: 0 additions & 24 deletions content/snippets/js/s/n-max-elements.md

This file was deleted.

24 changes: 0 additions & 24 deletions content/snippets/js/s/n-min-elements.md

This file was deleted.

27 changes: 27 additions & 0 deletions content/snippets/js/s/n-min-max-elements-in-array.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
---
title: "Tip: Find the n min or max elements in a JavaScript array"
shortTitle: N min or max elements of an array
type: tip
language: javascript
tags: [math,array]
author: chalarangelo
cover: digital-nomad-15
excerpt: Find the `n` minimum or maximum elements in a JavaScript array quickly and easily.
dateModified: 2023-10-05
---

We've previously covered [finding the minimum and maximum value in a numeric array](/js/s/array-min-max), but what if you need to find the `n` minimum or maximum values? Turns out it's almost as easy.

For either one of the operations, we'll first need to **sort the array in ascending or descending order**. This can be done using `Array.prototype.sort()` and the appropriate comparator function. However, we'll need to create a **shallow clone** of the array first using the spread operator (`...`) to avoid mutating the original array.

Then, we can use `Array.prototype.slice()` to get the first `n` elements of the sorted array. If `n` is not provided, we'll get the first element of the array. If `n` is greater than or equal to the length of the array, we'll get the original array back.

```js
const minN = (arr, n = 1) => [...arr].sort((a, b) => a - b).slice(0, n);
const maxN = (arr, n = 1) => [...arr].sort((a, b) => b - a).slice(0, n);

minN([1, 2, 3]); // [1]
minN([1, 2, 3], 2); // [1, 2]
maxN([1, 2, 3]); // [3]
maxN([1, 2, 3], 2); // [3, 2]
```
4 changes: 2 additions & 2 deletions content/snippets/js/s/number-is-even-odd.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ dateModified: 2023-10-06

### Using the modulo operator

The modulo operator (`%`) returns the remainder of a division operation. Given that, we can check if a number is even or odd by dividing it by `2` and checking the remainder. If the remainder is `0`, the number is even, otherwise it's odd.
The **modulo operator** (`%`) returns the **remainder of a division operation**. Given that, we can check if a number is even or odd by dividing it by `2` and checking the remainder. If the remainder is `0`, the number is even, otherwise it's odd.

```js
const isEven = num => num % 2 === 0;
Expand All @@ -24,7 +24,7 @@ isOdd(3); // true

### Using the bitwise AND operator

The bitwise AND operator (`&`) returns `1` if both bits are `1`, otherwise it returns `0`. The binary representation of an even number always ends with `0`, while the binary representation of an odd number always ends with `1`. As such, applying the bitwise AND operator to a number and `1` will return `0` for even numbers and `1` for odd numbers. In order to convert this result to a boolean, we can use the `Boolean()` function.
The **bitwise AND operator** (`&`) returns `1` if both bits are `1`, otherwise it returns `0`. The binary representation of an even number always ends with `0`, while the binary representation of an odd number always ends with `1`. As such, applying the bitwise AND operator to a number and `1` will return `0` for even numbers and `1` for odd numbers. In order to convert this result to a boolean, we can use the `Boolean()` function.

```js
const isEven = num => !Boolean(num & 1);
Expand Down

0 comments on commit 1aa4d25

Please sign in to comment.