chore: rename docs to resources

This commit is contained in:
Jean-Philippe Sirois
2019-07-29 20:48:30 -04:00
parent a833613b21
commit 8f771e194e
20 changed files with 50 additions and 50 deletions
@@ -0,0 +1,10 @@
---
authors:
- "Xetera#0001"
created_at: 2019/07/27
title: Callbacks
---
# Callbacks are everywhere
If you've been doing javascript for any amount of time you'll have noticed that callbacks appear in just about every single piece of code.
@@ -0,0 +1,195 @@
---
authors:
- "veksen#1060"
created_at: "2019/07/27"
---
# Iterative vs Functional array helpers
-- placeholder --
## find
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
let foundUser = null
users.forEach(user => {
if (user.name === "John") {
foundUser = user
}
})
```
Functional way:
```js
const foundUser = users.find(user => user.name === "John")
```
## filter
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
const youngerUsers = []
users.forEach(user => {
if (user.age < 18) {
youngerUsers.push(user)
}
})
```
Functional way:
```js
const youngerUsers = users.filter(user => user.age < 18)
```
## map
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
const userNames = []
users.forEach(user => {
userNames.push(user.name)
})
```
Functional way:
```js
const userNames = users.map(user => user.name)
```
## reduce
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
let totalAge = 0
users.forEach(user => {
totalAge += user.age
})
```
Functional way:
```js
const totalAge = users.reduce((acc, user) => acc + user.age)
```
## some
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
let hasYoungUsers = false
for (let i = 0; users.length > i; i++) {
if (user > 18) {
hasYoungUsers = true
break
}
}
```
Functional way:
```js
const hasYoungUsers = users.some(user => user.age < 18)
```
## every
```js
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
]
```
Iterative way:
```js
let allUsersAreOldEnough = true
for (let i = 0; users.length > i; i++) {
if (user.age > 18) {
allUsersAreOldEnough = false
break
}
}
```
Functional way:
```js
const hasYoungUsers = users.some(user => user.age < 18)
```
## inludes
```js
const pets = ["cat", "dog", "bat"]
```
Iterative way:
```js
let found = false
pets.forEach(pet => {
if (pet === "dog") {
found = true
}
})
// or most of the time done with indexOf
pets.indexOf("dogs") > 0
```
Functional way:
```js
pets.includes("dogs")
```
@@ -0,0 +1,107 @@
---
authors:
- "Xetera#0001"
created_at: 2019/07/26
updated_at: 2019/07/26
title: Introduction to Promises
recommended_reading:
- javascript/callbacks
- javascript/es6/arrow-functions
---
# A Promise to Keep
A `Promise` in Javascript represents an action that has already started, but one that will be
completed at a later time. Much like in real life, when you create a promise, you are expected
to fulfill that promise. However, sometimes things go wrong where you can no longer fulfill
a promise you made. This is essentially the main idea behind how promises work in javascript.
## Basics
When you create a Promise or call a function that returns a Promise in Javascript, you're left
with an object that can either resolve into the actual value that you were promised, or it
can reject and leave you with an error for why that promise failed.
We can access these values using the `.then` and `.catch` methods on the `Promise` object respectively.
## A Simple Example
First, let's explore a bit of a made-up example. Imagine we have a promise-returning function
called `getMembers` that retrieves all the members in a discord server. When we execute this
function we see the following result.
```js
const members = getMembers("The Programmers Hangout")
console.log(members) // Promise {<pending>}
```
Normally, we would have expected to see an array of all the members but it takes time to
get all the information about members so we're instead returned a Promise of members, rather
than the members themselves.
In order to access this information, we'll have to call the `.then` method on our `members` object
to access the actual members like so.
```js
getMembers("The Programmers Hangout").then(members => {
console.log(members) // (32k) [{...}, {...}, {...}]
})
```
This way we are able to make sure that we only try to `console.log` when the `getMembers` function has resolved and ready to be used.
## Beginner Mistakes
Promises are possibly the #1 most common source of confusion for beginners. In order
to avoid falling in pitfalls yourself, you have to remember 2 things about Javascript when
working with promises.
1. Javascript does not wait.
2. No seriously, Javascript won't wait for your promises!
You may have tried doing something like this before.
```js
// Incorrect code, don't copy!
let results
getWeather("Los Angeles").then(weather => {
results = weather
})
console.log(results) // undefined
```
Why is `results` undefined? Because **Javascript doesn't wait**. Whenever a Promise is created,
your code will continue to run until there's no more code left in the stack. Only then
will javascript try to run the `.then` callback of a Promise. Even if your Promise resolves
immediately you are going to have to wait until you've run all the code in the stack before
your `.then` callback has a chance to start running. This is due to the way the event loop works,
you can watch [this amazing talk](https://youtu.be/8aGhZQkoFbQ) on it to learn more.
In order to fix this problem we need to move the `console.log` inside the `.then` callback like so:
```js
getWeather("Los Angeles").then(weather => {
console.log(weather) // Sunny, probably
})
```
## Real World Example
Here is a real function that gets character information from the Rick and Morty API.
You can try it in your browser if you want to test it out.
```js
function getCharacters() {
return fetch(`https://rickandmortyapi.com/api/character`)
.then(response => response.json())
.then(response => response.results)
}
getCharacters().then(characters => {
console.log(characters) // (20) [{...}, {...}, {...}]
})
```
Let's break down what's happening in this function
// TODO: finish this
@@ -0,0 +1,75 @@
---
authors:
- "Xetera#0001"
created_at: "2019/07/26"
---
# Simplifying Promises
-- placeholder --
The first naive attempt, using new Promise for something that already returns a promise.
```js
function doAsync(number) {
return new Promise(function(resolve, reject) {
doDatabase().then(function(dbResult) {
otherDbFunction(dbResult).then(function(secondResult) {
resolve(secondResult + 10)
})
})
})
}
```
Turns out you don't need new Promise if you're working with a function that
already returns a promise, you can just return the original thing.
```js
function doAsync(number) {
return doDatabase().then(function(dbResult) {
otherDbFunction(dbResult).then(function(secondResult) {
return secondResult + 10
})
})
}
```
You also don't have to nest `.then` functions, the whole point of promises
is that they allow you do chain them sequentially.
```js
function doAsync(number) {
return doDatabase()
.then(function(dbResult) {
return otherDbFunction(dbResult)
})
.then(function(secondResult) {
return secondResult + 10
})
}
```
you also don't have to create a new function just to pass in one
variable, you can pass in the entire function itself to the then block
```js
function doAsync(number) {
return doDatabase()
.then(otherDbFunction)
.then(function(secondResult) {
return secondResult + 10
})
}
```
And you don't need those returns if you just have ES6 arrow functions
```js
const doAsync = number =>
doDatabase()
.then(otherDbFunction)
.then(secondResult => secondResult + 10)
```
Wow, that last one looks a lot cleaner to me than the first. Keeping that in mind, maybe we could be making some of our other functions cleaner as well
@@ -0,0 +1,115 @@
---
authors:
- "supergrecko#3434"
created_at: "2019/07/27"
---
# Singletons
A singleton is a class which is only instantiated once during runtime. This is done by keeping a static property containing its instance on the singleton class.
There are multiple benefits to using a singleton class
- You're always going to pull the same instance of the class
- It's only instantiated once
- Use `$this` in a static-like context
By using a singleton instead of a static class we expose a cleaner class to use and we can use regular instance properties instead of static properties.
# Creating a Singleton in PHP
Creating a class which can be used as a singleton is very simple.
```php
<?php
namespace Example;
class Singleton
{
/**
* The singleton instance
* @var Singleton
*/
private static $instance;
/**
* Get the instantiated singleton, or create it if it hasn't been instantiated yet.
* @return Singleton
*/
public static function getInstance(): Singleton {
// In PHP 7.4 we will be able to do
// static::$instance =?? new static();
// The double ?'s is a null-coalesce operator. There's a link about it below.
static::$instance = static::$instance ?? new static();
return static::$instance;
}
}
```
# Testing our Singleton
To give a little functionality to our freshly baked Singleton we add these three members to the class
```php
private $word = "Pineapple";
public function getWord(): string {
// PHP_EOL is a constant for a new line (\r\n) or whichever your OS uses.
return $this->word . PHP_EOL;
}
public function setWord(string $word): void {
$this->word = $word;
}
```
We are now ready to test our Singleton.
We'll start of by proving that only one instance is created during runtime. We'll grab the singleton instance twice using `Singleton::getInstance();` and comparing their object ids using `spl_object_hash`. Let's try it!
```php
$first = Singleton::getInstance();
$second = Singleton::getInstance();
// Compare the hash ids for each of the variables, if they are equal then they contain the same instance.
var_dump(spl_object_hash($first) === spl_object_hash($second)); // bool(true)
```
We can now prove its static-like functionality by using our `getWord` and `setWord` methods.
We will do this by comparing the returned value from `getWord()` on `$first` and `$second`.
```php
var_dump($first->getWord() === $second->getWord()); // bool(true)
// now let's try chaning the value on $first
$first->setWord("Banana");
// the test will still pass, because it's a singleton.
var_dump($first->getWord() === $second->getWord()); // bool(true)
```
# Further Research
Here's a couple links which will help you understand Singletons better.
## Singleton Resources:
- https://en.wikipedia.org/wiki/Singleton_pattern
- https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php
- https://phptherightway.com/pages/Design-Patterns.html#singleton
## Static Keyword Resources:
- https://www.php.net/manual/en/language.oop5.static.php
- https://www.php.net/manual/en/language.oop5.late-static-bindings.php
- https://en.wikipedia.org/wiki/Static_(keyword)
## The Null-Coalescing Operator Resources:
- https://en.wikipedia.org/wiki/Null_coalescing_operator
- https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
+14
View File
@@ -0,0 +1,14 @@
---
authors:
- "Xetera#0001"
date: 2019/06/26
---
# Python
This is a placeholder post
```py
def test():
return "Hello world"
```