Javascript
Javascript¶
https://www.htmhell.dev/adventcalendar/2023/2/
The easiest way to learn & practice modern JavaScript
How to chain multiple functions properly with await/async
Variables¶
Remove Non Attribute errors:
//Return undefined instead of error when attribute does not exist
let fightskill = actor.data.data.attributes.fight?.value
Array/Dictionary Functions¶
Map:
//Take the controlled_tokens array do a function on each element in the array
let actors = canvas.token.controlled.map(token => {
//Take the input data and get the actor value and return
return token.actor
})
Filter:
//Reduce the array of items by a comparison
let actors = currentactor.items.filter(item => item.data.data.attributes.type?.value == "weapon")
Every:
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
````
**For Each:**
```js
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
Keys:
const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();
for (const key of iterator) {
console.log(key);
}
// expected output: 0
// expected output: 1
// expected output: 2
Loop through Objects:
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Async¶
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function
If you're doing nothing in between your async calls, using .then/.catch might be simpler.
Properly Chaining Calls:
const getDependentData = async () => {
const user = await userName()
const addy = await userAddress(user.uid)
const city = await userName(addy.zip)
return city
}
Promises¶
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Properly Paralyzing Functions:
const [user, products] = await Promise.allSetted([
getUser(), getProducts()
]).then((results) => results.forEach((result) => console.log(result.status)))
Promise Heaven:
Promise.resolve(5)
.then((val) => val + 3)
.then((num) => String(num))
.then((str) => `I have ${str} llamas`)
.then((str) => /ll/.test(str))
JSON¶
Convert from String:
var obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
Convert to String:
var myJSON = JSON.stringify({name:"John", age:30, city:"New York"});
Modules¶
Import files over HTTP
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules
Sample HTML:
<!DOCTYPE html>
<html>
<head>
<link href="./node_modules/@schedule-x/theme-default/dist/index.css">
<script type="importmap">
{
"imports":{
"preact":"./node_modules/preact/dist/preact.js",
"preact/hooks":"./node_modules/preact/hooks/dist/hooks.js",
"@preact/signals":"./node_modules/@preact/signals/dist/signals.js",
"@schedule-x/calendar":"./node_modules/@schedule-x/calendar/dist/core.umd.js",
"tsdav":"./node_modules/tsdav/dist/tsdav.js"
}
}
</script>
<script type="module" src="dev.js"></script>
</head>
<body>
<div id="calendar"></div>
</body>
</html>
dev.js:
import { createDAVClient } from 'tsdav';