Last active
January 12, 2020 08:18
-
-
Save sashee/b31df3c07d4a794cdf8bb00e96acd6eb to your computer and use it in GitHub Desktop.
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script> | |
console.log = (msg) => document.body.innerText += `${msg}\n`; | |
// utility function for sleeping | |
const sleep = (n) => new Promise((res) => setTimeout(res, n)); | |
(async () => { | |
const double = (str) => { | |
return str + str; | |
}; | |
console.log(double("abc")); | |
// abcabc | |
// https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest | |
const digestMessage = async (message) => { | |
const msgUint8 = new TextEncoder().encode(message); | |
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); | |
const hashArray = Array.from(new Uint8Array(hashBuffer)); | |
const hashHex = hashArray.map(b => b.toString(16).padStart(2, "0")).join(''); | |
return hashHex; | |
}; | |
console.log(await digestMessage("msg")); | |
// e46b320165eec91e6344fa10340d5b3208304d6cad29d0d5aed18466d1d9d80e | |
const strings = ["msg1", "msg2", "msg3"]; | |
console.log(strings.map(double)); | |
// ["msg1msg1", "msg2msg2", "msg3msg3"] | |
console.log(await strings.map(digestMessage)); | |
// [[object Promise],[object Promise],[object Promise]] | |
console.log("\nfor iteration"); | |
// synchronous | |
{ | |
const res = []; | |
for (let i of [1, 2, 3]){ | |
res.push(i + 1); | |
} | |
console.log(res); | |
// res: [2, 3, 4] | |
} | |
// asynchronous | |
{ | |
const res = []; | |
for (let i of [1, 2, 3]){ | |
await sleep(10); | |
res.push(i + 1); | |
} | |
console.log(res); | |
// res: [2, 3, 4] | |
} | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment