-
Notifications
You must be signed in to change notification settings - Fork 12.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
11 changed files
with
158 additions
and
175 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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] | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters