feat(resources): split up topics and languages

This commit is contained in:
Jean-Philippe Sirois
2020-05-27 02:42:39 -04:00
parent 8fba0edc4f
commit 135452bd4b
35 changed files with 86 additions and 55 deletions
@@ -0,0 +1,33 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: C++
---
###### Beginner
- [Get started](https://isocpp.org/get-started)
- [Learn C++](http://www.learncpp.com/)
- [C++ tutorial](http://www.cplusplus.com/doc/tutorial/)
###### Documentation
- [C++ reference](http://en.cppreference.com/w/)
- [https://isocpp.org/std/the-standard](https://isocpp.org/std/the-standard)
- [http://eel.is/c++draft/](http://eel.is/c++draft/)
###### Books
- [The definitive C books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282)
###### Video
- [TPH Picks](https://goo.gl/emLpwP)
- [Cherno](https://www.youtube.com/playlist?list=PLlrATfBNZ98dudnM48yfGUldqGD0S4FFb)
###### Other
- [Super FAQ](https://isocpp.org/wiki/faq)
- [Compilers](http://www.stroustrup.com/compilers.html)
- [Design guidelines](https://github.com/isocpp/CppCoreGuidelines)
@@ -0,0 +1,152 @@
---
authors:
- "alearori#8661"
created_at: 2019/11/15
title: "Multidimensional Arrays"
---
## What is a multidimensional array?
To put simply, a multidimensional array is an array that contains another array of another array... of another array of objects. It is commonly used for making matricies, but it can also be used for storing information such as `string`.
The format of the container looks like:
`{{a1,a2,a3,...},{b1,b2,b3,...},{c1,c2,c3,...},...}`
Where `a1`,`a2`,`a3`, and etc. are objects of the data type that was array was declared to contain at the start.
But they can also be another array whch contains objects of said data type. Which looks like this:
`{{{a1,a2,a3,...},{b1,b2,b3,...},{c1,c2,c3,...},...},...}`
And we can keep going on and on, creating more arrays inside the arrays.
### How do we make one?
To create multidimensional array, you do it like a regular array but with a extra `[]` at the end.
#### Method 1:
Use
```c++
data_type array_name[A][B];
```
Where `data_type` is an data type(such as `int`, `char` or etc.), `array_name` is what the name of the array will be and `A` and `B` are non-negative integers, where `B` is the number of objects within that layer and `A` is the number of `B`'s within this array.
Example 1:
```c++
int arr[2][3];
```
This will make a empty 2x3 matrix that looks like:
```c++
{{0,0,0},{0,0,0}}
```
So there are 2 arrays with 3 elements each within the array `arr`.
#### Method 2:
Use:
```c++
data_type array_name[][] = {{a1,a2,a3,...},{b1,b2,b3,...}};
```
Where `data_type` is an data type(such as `int`, `char` or etc.), `array_name` is what the name of the array will be and `a1, a2, a3, b1, b2, b3,...` are objects of the data type that was chosen at the start in `data_type`, but the number of `a`'s and `b`'s must be equal.
Example 2:
```c++
int arr[][] = {{1,2,3},{4,5,6}};
```
This will make a 2x3 matrix with preset values instead of all 0's so it'll look like:
```c++
{{1,2,3},{4,5,6}}
```
#### Method 3:
Combine both:
```c++
data_type array_name[A][B] = {{a1,a2,a3,...},{b1,b2,b3,...}}
```
Where `data_type` is an data type(such as `int`, `char` or etc.), `array_name` is what the name of the array will be and `a1, a2, a3, b1, b2, b3,...` are objects of the data type that was chosen at the start in `data_type` and `A` and `B` is the number of `{}`'s and `a`'s and `b`'s respectively.
Example 3:
```c++
int arr[2][3] = {{1,2,3}, {4,5,6}};
```
This will make a 2x3 matrix that looks like:
```c++
{{1,2,3},{4,5,6}}
```
#### Note:
It is possible to go ever further, and so a declaration like `data_type array_name[A][B][C]` is possible and would add more layers to your array. So after going through one layer, you have to input the location of the next layer, and so on and so forth until you reach the deepest layer of the `{}` where you'll find the object.
Example 4:
```c++
int arr[2][3][4];
```
This will make an 2x3x4 matrix that looks like:
```c++
{{{0,0,0,0},{0,0,0,0},{0,0,0,0}},{{0,0,0,0},{0,0,0,0},{0,0,0,0}}}
```
## What can you do with it?
#### Calling objects
To get the object inside, you can call for the object inside a multidimensional array by putting a integer inside the `[]`.
So taking the array made in example 2 above:
```c++
int arr[2][3] = {{1,2,3}, {4,5,6}};
std::cout << arr[0][1];
```
This would output `2` because using array indicies, `2` is the object in position 1 of the 0th array.
You must put an integer in both `[]`, or else you will get an error.
There is no syntax to instantly view the whole array, but an easy way is to loop through the whole array and outputting it.
#### Reassigning objects
Like with a regular array, you can also reassign what object is being held inside a exact position using `=`
So let's take for example the array made in example 2 above, which looks like:
```c++
int arr[2][3] = {{1,2,3}, {4,5,6}};
arr[1][1] = 1337;
```
This would cause the array to change to looking like:
```c++
{{1,2,3},{4,1337,6}}
```
## Restrictions
1. The size is locked upon initialization. Once you make the array, its size is locked. For example, if you make a 2x3 array, and realize you need another column or row, you have to either make a new one, or change the size where you initialize it. If you want a dynamic size array, a array which you can change the size of, consider using `std::vector` instead.
2. There is no way to search except by iterating through each object in the entire array. For example, if you need to find the number `2` in:
`{{1,2,3},{4,5,6}}`, you need to go through every element in the array, such as in a nested `for` loop, to find the position(s) where `2` is located.
3. No way to organize. Unlike with a `class`, you cannot designate a column with something like a name or title. For example, if you want to make one array store student IDs and their grade, you have to note that the first array is the student ID and second array is their grade.
4. No on-demand sorting. Unlike other containers, multidimensional arrays do not come with a built-in sorting function, such as highest to lowest or vice versa. It is stuck in that format unless you create your own sorting functions that take the array and sort it. Meanwhile, other standard library data structures such as `std::vector`, do have built in sorting functions, so you can use those opposed to an array.
5. Unlike with other container types, an array cannot hold anything other than the original data type, so if you declare it to be of data type `int` at the start, it cannot hold anything else except integers inside. If you're looking to store multiple data types, you should make a `class`, `struct` or use other container types like `std::map` that fulfill your requirement.
@@ -0,0 +1,39 @@
---
authors:
- "sudonym#8623"
created_at: 2019/10/6
title: "pragma once"
---
## What is `#pragma once`?
The `#pragma once` directive tells a compiler to only include and parse a header file _once_ even if it is included multiple times in the same source file.
They provide a cleaner alternative to [include-guards](https://en.wikipedia.org/wiki/Include_guard) that are conventionally used for this purpose.
### Is it portable ?
No. `#pragma` directives are used to control _implementation-defined_ behavior and are thus compiler-specific.
### Why should I use it ?
1. Less typing if your IDE/editor doesn't do it for you ¯\\\_(ツ)\_/¯
2. Faster compiling, as the compiler can now completely ignore processing/loading this file, it'd have to load it all if you were using a header guard.
3. You find header guards icky.
### Why should I not use it ?
1. You want to be standards-compliant
2. You want to follow CppCoreGuidelines: <https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#Rs-guards>
3. You use a `compiler:version` which doesn't support `pragma once` or has a buggy implementation (see the section on compiler support)
### Why not both?
![Why not both](https://i.imgur.com/DBcUtoo.png)
Some people/projects do this, so that you can both be standards-compliant (since unrecognized pragmas will be ignored) _and_ get that speed bonus.
I can't tell you if you should either use pragma, header guards or both, that's just one of those opinion topics nobody agrees on.
### What compilers support it?
Virtually all popular and modern compilers.
See [this list](https://en.wikipedia.org/wiki/Pragma_once#Portability) for more information.
@@ -0,0 +1,160 @@
---
authors:
- "AstronautEVA#0331"
title: "Classes"
created_at: 2019/10/20
---
## What is a class?
Oftentimes in programs, it is necessary to represent objects from the real world as computer data.
For example, if someone is writing a program that simulates a zoo, they will need to create some animals.
A class is a way to write the blueprint of whatever you are trying to represent; in our case it would be a blueprint of an animal.
Let us investigate what an animal class might look like.
First we will declare attributes that an animal would have. There are many attributes we could list, but let's choose 3.
The animal will have a
- name (because zoos name their animals)
- age
- weight
All of these words are nouns which is a hint that they should be implemented as variables.
```java
public class Animal {
public String name;
public int age;
public float weight;
}
```
Notice that we have only declared these variables, we did **not** initialize them (set them equal to a value).
Okay so we have added attributes to our animal which is great, but we want our animal to actually be able to _do_ things. Let's pick 2
things we want our animal to do.
Our animal should
- move
- sleep
These are verbs which means they likely need to be implemented as methods.
```java
public class Animal {
public String name;
public int age;
public float weight;
public void move() {
System.out.println("The animal moves.");
}
public void sleep() {
System.out.println("The animal sleeps.");
}
}
```
## Class vs Object
Remember this is only the description of what an animal is, not a specific animal. A specific animal such as Max is one instance of a class and is called an object. It has values assigned to its attributes like the name is Max and the age is 5. You can call methods on the object such as move or sleep. And there can be an infinite number of objects constructed from a class. To create objects from your class, you need something called a constructor.
The format of a constructor looks like this:
```java
public ClassName() {
}
```
It should be public, have no return type, and the name of the method should be the same name as the class.
Since the constructor is called when you want to create an object of a class, and you will likely want that object to have specific values for its attributes (such as making the name be "Max"), you need the constructor to initialize the variables of the object. One way to do this is by giving the constructor parameters that you will use to pass in the values you want for your object.
Modifying our constructor template from above to do this might look like:
```java
public ClassName(String myObjectsName) {
name = myObjectsName;
}
```
Now that you've got a general idea of what a constructor should look like, we will apply this to our Animal class.
```java
public class Animal {
public String name;
public int age;
public float weight;
// here is the constructor
public Animal(String name, int age, float weight) {
/*
Since we used the same name for the parameters as we did the class variables, we have
to use the word "this" to differentiate between which variable we are talking about.
"this" refers to the Animal class, so stating "this.name" refers to the name variable
declared at the top of the Animal class.
Stating "name" without "this" refers to the parameter variable called name.
*/
this.name = name; // set the class variable called name equal to the value of the parameter called name
this.age = age;
this.weight = weight;
}
public void move() {
System.out.println("The animal moves.");
}
public void sleep() {
System.out.println("The animal sleeps.");
}
}
```
Our class is finally ready to use! Let's add in a main method to our class so we can create some objects and see what happens.
```java
public class Animal {
public String name;
public int age;
public float weight;
public Animal(String name, int age, float weight) {
this.name = name;
this.age = age;
this.weight = weight;
}
public void move() {
System.out.println("The animal moves.");
}
public void sleep() {
System.out.println("The animal sleeps.");
}
public static void main(String[] args){
// create a variable of type Animal by calling the constructor of the Animal class
Animal myAnimal = new Animal("Max", 5, 10.3);
// access the variables of the object you just created
myAnimal.name; // returns "Max"
myAnimal.age; // returns 5
myAnimal.weight; // returns 10.3
// change a variable of the object
myAnimal.name = "JoJo";
myAnimal.name; // returns "JoJo"
// call the functions of the object you just created
myAnimal.move(); // returns "The animal moves."
myAnimal.sleep(); // returns "The animal sleeps."
// create as many Animal objects as you want
Animal foo = new Animal("Polly", 34, 1.4);
Animal bar = new Animal("Sophie", 8, 89.7);
foo.name; // returns "Polly"
bar.name; // returns "Sophie"
}
}
```
@@ -0,0 +1,144 @@
---
authors:
- "supergrecko#3434"
created_at: "2019/10/04"
title: Generics
---
## What are generics?
Generics is a concept in programming which allows passing a type argument to a class or a method.
Java's standard library makes heavy use of generics to reduce repetition and to provide flexibility.
Here's an example where Java uses generics.
```java
class Main {
public static void main(String[] args) {
List<String> = new ArrayList<String>();
}
}
```
In this example we are passing the String type to the List class. We can now say we have "A List of Strings".
## Why should we use generics?
By using generics we can provide type safety while having reusable code.
Lets say we want to create coffee capsule, We want one holder for Espresso capsules and one for Cappuccino capsules. This is one way we can implement this coffee capsule holder.
For this example we will use these classes to represent our coffee capsules.
```java
class EspressoCapsule {}
class CappuccinoCapsule {}
```
```java
import java.util.ArrayList;
// An espresso capsule holder
class EspressoHolder {
// This is a generic. ArrayList of EspressoCapsules
private ArrayList<EspressoCapsule> capsules = new ArrayList<EspressoCapsule>();
public EspressoHolder(EspressoCapsule capsule) {
this.capsules.add(capsule);
}
}
// A cappuccino capsule holder
class CappuccinoHolder {
// This is a generic. ArrayList of CappuccinoCapsules
private ArrayList<CappuccinoCapsule> capsules = new ArrayList<CappuccinoCapsule>();
public CappuccinoHolder(CappuccinoCapsule capsule) {
this.capsules.add(capsule);
}
}
```
We can now use these capsule holders like this:
```java
class Main {
public static void main(String[] args) {
EspressoHolder espresso = new EspressoHolder(new EspressoCapsule());
CappuccinoHolder cappuccino = new CappuccinoHolder(new CappuccinoCapsule());
}
}
```
The only concern here is that we're repeating a lot of code. Almost the entire `EspressoHolder` implementation is copied into the `CappuccinoHolder` implementation.
Next up we'll take a look at an implementation which uses generics to avoid this repetitive behavior.
## Optimizing our Coffee brewer with Generics
What if we could have a single Holder class for both types of capsules? Let's implement that by using generics.
Let's start off by removing both the `CappuccinoHolder` and the `EspressoHolder` classes. We're now left with this:
```
import java.util.ArrayList;
class EspressoCapsule {}
class CappuccinoCapsule {}
```
We can now implement our brand new `Holder` class. We'll start of by making the class accept a generic type.
```java
class Holder<T> {
}
```
This creates a new data type inside the Holder class named `T`.
We now expect users to create a `Holder` instance via this syntax. String in this example can be replaced with any type.
```java
Holder<String> holder = new Holder<String>();
```
In this scenario, `T` inside the Holder instance will be the String type.
Let's add our ArrayList again.
```java
class Holder<T> {
private ArrayList<T> capsules = new ArrayList<T>();
}
```
Notice how we're passing T further down into the ArrayList generic? That means the ArrayList generic type will also change based on the Holder generic type.
We can now finish up our holder implementation like this.
```java
class Holder<T> {
private ArrayList<T> capsules = new ArrayList<T>();
public Holder(T capsule) {
this.capsules.add(capsule);
}
}
```
Because T is a qualified type inside our Holder class we can also make the constructor accept the T type as an argument.
This is our new way of using the Holder class.
```java
class Main {
public static void main(String[] args) {
Holder<CappuccinoCapsule> cappuccino = new Holder<CappuccinoCapsule>(new CappuccinoCapsule());
Holder<EspressoCapsule> espresso = new Holder<EspressoCapsule>(new EspressoCapsule());
}
}
```
We just reduces the amount code required to hold our two capsule types in by 50%. The cool thing is that we're now able to create as many capsule types as we want while being able to stick to our Holder implementation. We could have 20 different capsule types, our `Holder` class would be able to take care of all of them.
@@ -0,0 +1,157 @@
---
authors:
- "AstronautEVA#0331"
title: "Inheritance"
created_at: 2019/10/24
recommended_reading:
- java/class
---
## What is Inheritance?
Inheritance is the idea that when two classes have similar implementations, rather than duplicating code for each class one can obtain it from the other. Much like a human child will inherit traits from their parents, a child class will inherit data from
its parent class.
Here is an example of a class hierarchy:
```sh
Animal
_____|______
| |
Bird Reptile
```
Animal is the parent class (also called the superclass), Dog and Bird are both child classes (also called subclasses).
**NOTE:** A child class will only have 1 direct parent (known as single inheritance), not more.
Here is an example of an illegal class hierarchy in Java:
```sh
// THIS IS ILLEGAL
// A child can only have 1 parent.
Mammal Fish
|____________|
|
Otter
```
However, there can be many children.
```sh
Animal
_____|______
| |
Bird Reptile
| ____|____________
| | | |
Eagle Snake Frog Lizard
```
Now Eagle is a child of Bird, and Bird is the parent of Eagle. Bird is also a child of Animal. Similarly Snake, Frog, and Lizard are
children of Reptile, Reptile is each one's parent, and Reptile is also the child of Animal.
To understand what the children inherit, let's define our Animal class.
```java
public class Animal {
public int age;
}
```
This is a very simple class and only has one field. In our hierarchy we see that Bird is a child of Animal. To define a subclass we
must use the keyword `extends` in the format of `public class ChildClass extends ParentClass`. The `extends` keyword signifies an is-a
relationship. The child class **is a** type of the parent class. A bird **is a** type of animal.
```java
public class Bird extends Animal {
}
```
As you can see we have not placed anything in the Bird class. But this does not mean the Bird class has no fields or methods. Since
Bird inherits from Animal, it has the age field defined in the Animal class. **NOTE:** The subclass will inherit all the _public_ fields and methods of the parent class, but never the constructors.
```java
Animal myAnimal = new Animal();
myAnimal.age //returns 0
Bird myBird = new Bird();
myBird.age //returns 0
```
Let's say we want to keep track of the size of a bird's wingspan. We will implement this as a variable called `wingspan`. Since
only birds have a wingspan and not every animal, we will put this variable in the Bird class.
```java
public class Bird extends Animal {
public float wingspan;
}
```
If we create an object of type Bird it will have 2 variables. If we create an object of type Animal it will have 1.
```java
Animal myAnimal = new Animal();
myAnimal.age //returns 0
myAnimal.wingspan //produces an error because the variable doesn't exist
Bird myBird = new Bird();
myBird.age //returns 0
myBird.wingspan //returns 0.0
```
Things can get a little bit confusing when trying to understand what you can access from an object. Just remember that you will only be able to access the fields/methods that correspond to the object's _type_. Also, inheritance works in one direction; the children reach up to get the fields/methods from their parent, but the parent cannot reach down to get fields/methods from their children.
```java
Animal myAnimal = new Animal(); //myAnimal only has the age variable and you can access it
Animal myAnimal = new Bird(); //you can only access the age variable since the object is of type Animal. the object does have the wingspan variable due to calling the Bird() constructor, but you cannot access it.
Bird myBird = new Bird(); //myBird has both the age and wingspan variables since you called the Bird() constructor and Bird inherits from Animal. you can access both variables since the object type is Bird.
Bird myBird = new Animal(); //this produces an error because the object type is Bird which means constructor Animal() does not exist (constructors are not inherited).
```
All of the above examples using public variables also works when using public methods.
If we define a method in our superclass:
```java
public class Animal {
public int age;
public void sleep() {
System.out.println("The animal sleeps.");
}
}
```
It can be used in our subclass.
```java
Animal myAnimal = new Animal();
myAnimal.sleep(); // returns "The animal sleeps."
Bird myBird = new Bird();
myBird.sleep(); // returns "The animal sleeps."
```
But if we define a method in our subclass:
```java
public class Bird extends Animal {
public float wingspan;
public void chirp(){
System.out.println("The bird chirps.");
}
}
```
It cannot be used in our superclass.
```java
Animal myAnimal = new Animal();
myAnimal.chirp(); // error, the method does not exist
Bird myBird = new Bird();
myBird.chirp(); // returns "The bird chirps."
```
One final thing to note about inheritance is that in Java, every class inherits from a class called Object (java.lang.Object) even when
it is not explicitly stated via `extends`. You can read what your class inherits from java.lang.Object in [the official docs](https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html).
@@ -0,0 +1,35 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: Java
---
###### Documentation
- [Java docs](https://docs.oracle.com/en/java/javase/11/)
###### Free Books
- [https://goo.gl/WZTC9C](https://goo.gl/WZTC9C)
###### Video
- [EJ Media](https://goo.gl/tC1KwC)
- [Derek Banas](https://goo.gl/9eVFkE)
- [Free With Registration | Cave of Programming](https://goo.gl/NXTo4H)
###### Guides
- [Learn By Examples | Beginnersbook.com](https://goo.gl/3nDWeQ)
###### Useful Repositories
- [Frameworks](https://goo.gl/EoLvrH)
- [Design patterns](https://goo.gl/wT7SfQ)
###### Other
- [History of Java](https://en.wikipedia.org/wiki/Java_version_history)
- [Wikibooks](https://en.wikibooks.org/wiki/Java_Programming/History)
- [Timeline](https://oracle.com.edgesuite.net/timeline/java/)
@@ -0,0 +1,63 @@
---
authors:
- "KaeseKuchenDEV#6322"
title: "An introduction to Streams"
created_at: 2019/12/15
external_resources:
- text: Java8 Stream Tutorial
href: https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/
---
Basically everyone, who spent a few hours coding some Java came across a situation like this:
```java
int[] intArray = {1,2,3,4,5};
for(int i = 0; i < intArray.length; i++) {
System.out.println(intArray[i]);
}
```
So, you need to print every element in an array, a list or any other data structure. But there has to be a nicer way to do this, especially with less code. Since Java 8 we are able to use so called "Streams" in Java. In particular the same result as from the code above can be achieved with this code:
```java
int[] intArray = {1,2,3,4,5};
Arrays.stream(intArray).forEach(n -> System.out.println(n));
```
You just made one line out of three. But how does this work? `int[] intArray = {1,2,3,4,5};` does just declare and initialize a new array of integers. This stays the same as before, because you can use the `Arrays.stream()` method for every Array, [as it works with generic Arrays](https://www.mkyong.com/java8/java-how-to-convert-array-to-stream/). This method creates a [Stream Object](https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html), that has several methods to perform operations on an array.
## Sorting
Now maybe you have a list instead of an array and you also want the list to get sorted before you print it. Without Streams you would first have to sort the list and then iterate through it. Way too many lines! Using Streams you can simply do:
```java
ArrayList<Integer> intList = new ArrayList<>();
intList.add(4);
intList.add(8);
intList.add(3);
intList.add(6);
intList.stream().sorted().forEach(n -> System.out.print(n + ", "));
```
At the end, you have again only one line, for sorting and printing every element in a list. Due to the fact that Streams mostly use Method Chaining, you could perform a bunch of operations.
## Filtering
Now you are able to print out every element of an array, a list, a stack, etc. sorted as well as unsorted. The last essential operation is, how to filter your array/list. One often has to only get specific elements of an array. Using Streams you could do it like this:
```java
String[] stringArray = {"The", "programmers", "Hangout"};
Arrays.stream(stringArray).filter(s -> Character.isUpperCase(s.charAt(0))).forEach(n -> System.out.println(n));
```
This prints:
`The`
`Hangout`
Since those two strings of the array begin with an uppercase letter.
Basically many methods of Stream use [lambda expressions](https://www.geeksforgeeks.org/lambda-expressions-java-8/). Using these in the `filter()` method, you can create very specific filters for your array, which can be compared to database operations in for Example SQL.
These are only a few examples on how to use Streams in Java, but those can already be very powerful and can make your code look way better and shorter. If you want to dive deeper into Streams, I would recommend you: https://winterbe.com/posts/2014/07/31/java8-stream-tutorial-examples/, as it deals with most of the possibilities of Streams.
@@ -0,0 +1,87 @@
---
authors:
- "T0M#5956"
- "Hayden#5036"
created_at: 2019/10/08
updated_at: 2019/10/13
title: Arrow functions
---
## Arrow Function Syntax
Brought into ES6, arrow functions are a new way to declare functions, and allow for shorter syntax. For example, below is a regular function, as usually seen before ES6.
```js
const sayHello = function () {
console.log("hello");
};
```
The same function can be rewritten with arrow function syntax, as seen below.
```js
const sayHello = () => {
console.log("hello");
};
```
Parameters are listed between the parentheses, in the same way a regular function does it:
```js
const sayHello = (nameOne, nameTwo) => {
console.log(nameOne, "says hello to", nameTwo);
};
```
For a single parameter, the parentheses can be omitted:
```js
const sayHello = (name) => {
console.log("hello", name);
};
```
Another interesting feature that also reduces the syntax within arrow functions, is that if the function is an expression, you can omit the `return` keyword and the curly braces. In arrow functions without braces, the `return` is implicit, meaning you don't need to include the `return` keyword. The following function returns "hello":
```js
const sayHello = () => "hello";
```
The same is also true of functions returning an expression using parameters, too.
```js
const sayHello = (name) => `hello ${name}`;
```
Or even...
```js
const helloObject = (name) => ({
isGreeting: true,
helloName: name,
});
```
This is essentially wrapping an object expression inside a grouped expression, causing it to return an object instead of expanding into a whole function body.
Long story short, we heard you liked expressions, so we put an expression inside your expression to give you nicer expressions.
## Handling of the Keyword This
The keyword `this` is handled differently in arrow functions. In an arrow function, `this` inherits its binding from the parent scope. That means that the keyword `this` inside of an arrow function references the same object that it does immediately outside of the arrow function where the arrow function is declared. On the other hand, when you use the older `function` syntax, `this` typically refers to the object that the function was called on, if the function is called as an instance method. If the function is not called as an instance method, `this` will usually be undefined (though it is possible to use functions like `call` or `bind` to manually provide a binding).
Using regular anonymous function, `this` is refers to the `HTMLButtonObject` that called it, and therefore the function outputs `[object HTMLButtonElement]` to the console.
```js
document.querySelector("#btn").addEventListener("click", function () {
console.log(this); // outputs "[object HTMLButtonElement]"
});
```
However, if an arrow function is used, `this` would refer to `[object Window]`, as that is the object that defined the function.
```js
document.querySelector("#btn").addEventListener("click", () => {
console.log(this); // outputs "[object Window]"
});
```
@@ -0,0 +1,33 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: Javascript
---
###### Documentation
- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
- [jQuery](https://contribute.jquery.org/documentation/)
- [NodeJS](https://nodejs.org/en/docs/)
- [Typescript](https://www.typescriptlang.org/docs/home.html)
- [Discord.js](https://discord.js.org/#/docs/main/stable/general/welcome)
###### Tutorials
- [Eloquent](https://eloquentjavascript.net/)
- [You Don't Know JS](https://github.com/getify/You-Dont-Know-JS)
- [MDN](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps)
- [Modern JS](https://javascript.info/)
- [Evie's Accelerated JS Tutorial](https://evie.gitbook.io/js/)
###### Discord.js
- [An Idiot's Guide](https://anidiots.guide/)
- [Discord.js Guide](https://discordjs.guide/)
###### Other
- [You might not need jQuery](https://youmightnotneedjquery.com/)
- [You might not need jQuery 2](https://github.com/you-dont-need-x/you-dont-need-jquery)
- [CodingTrain | tutorials with examples using p5.js](https://www.youtube.com/user/shiffman)
@@ -0,0 +1,232 @@
---
authors:
- "veksen#1060"
- "supergrecko#3434"
created_at: "2019/07/27"
title: Iterative vs Functional array helpers
---
This article assumes that you are comfortable with the very basics of JavaScript arrays, and how they differ to objects. This article teaches you how to use the built-in functions for arrays.
Each of the functions described in this article use a callback function. If you are not familiar with callback functions I would advise you to read [this article by Mozilla](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function) before continuing.
## Getting a specific element using `find()`
It's not rare to need to look for some specific element based on a criteria. `find()` makes this particularly easy. It takes a function, taking a few arguments:
- current item
- index of current item (optional)
- original array reference (optional)
The `.find()` function loops over the items, if the callback function evaluates to truthy the item is returned, and the loop ends.
If no items evaluated to truthy `undefined` will be returned.
If you're only interested in the presence of an element, consider using `some()`, which instead returns a boolean.
Conventionally, in an iterative approach, this would be done using a preset variable, and looping through our array.
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const foundUser = users.find((user) => user.name === "John");
// iterative way
let foundUser = null;
users.forEach((user) => {
if (user.name === "John") {
foundUser = user;
}
});
console.log(foundUser); // outputs { name: "John", age: 17 }
```
## Keep specific items using `filter()`
`filter()` makes it easy to keep specific items based on a criteria.
It takes a function, taking a few arguments:
- current item
- index of current item (optional)
- original array reference (optional)
`filter()` does not modify (mutate) the original array, instead, it returns a new one.
If the callback function evaluates to truthy, this specific item is pushed to the final array, otherwise it is ignored.
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const youngerUsers = users.filter((user) => user.age < 18);
// iterative way
const youngerUsers = [];
users.forEach((user) => {
if (user.age < 18) {
youngerUsers.push(user);
}
});
console.log(youngerUsers); // outputs [ { name: "John", age: 17 }, { name: "Jane", age: 16 } ]
```
## Modifying all elements of an array using `map()`
It's common to want to modify every element of an array with some logic, and `map()` makes this easy.
It takes a function, taking a few arguments:
- current item
- index of current item (optional)
- original array reference (optional)
The function loops through the array and runs the callback function on each element. Just like the `filter()` function, `map()` does not mutate the original array.
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const userNames = users.map((user) => user.name);
// iterative way
const userNames = [];
users.forEach((user) => {
userNames.push(user.name);
});
console.log(userNames); // outputs [ "Joe", "John", "Jane" ]
```
## Running custom logic using an array using `reduce()`
`reduce()` is often less understood, but it's not that complicated once you get the basics. Itself, it takes 2 arguments, a function, and an initial value. The function takes a few arguments:
- accumulator, that is a reference to the current value that was last returned, or the initial value
- current value, the currently looped element
- current index (optional)
- original array (optional)
The `reduce()` function returns the accumulative result after the callback has been ran on each element.
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const totalAge = users.reduce((acc, user) => acc + user.age, 0);
// iterative way
let totalAge = 0;
users.forEach((user) => {
totalAge += user.age;
});
console.log(totalAge); // outputs 58
```
## Checking if any element matches a condition with `some()`
`some()` is very similar to `find()`, except it returns a boolean on a match.
Conventionally, we would prepare some variable with a value of false, loop over all of the elements, and exit the loop once we find a match. The function takes a callback function which accepts some parameters.
- the current element
- the array index of the current element (optional)
- a reference to the array (optional)
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const hasYoungUsers = users.some((user) => user.age < 18);
// iterative way
let hasYoungUsers = false;
for (let i = 0; users.length > i; i++) {
if (user.age < 18) {
hasYoungUsers = true;
break;
}
}
console.log(hasYoungUsers); // outputs true
```
## Checking if all elements match a condition with `every()`
`every()` is similar to `some()`. The difference is that `some()` test if one or more of the items match. `every()` tests if every item in the array matches.
```js
// given our data
const users = [
{ name: "Joe", age: 25 },
{ name: "John", age: 17 },
{ name: "Jane", age: 16 },
];
// functional way
const allUsersAreOldEnough = users.every((user) => user.age < 18);
// iterative way
let allUsersAreOldEnough = true;
for (let i = 0; users.length > i; i++) {
if (user.age < 18) {
allUsersAreOldEnough = false;
break;
}
}
console.log(allUsersAreOldEnough); // outputs false
```
## Checking if an array contains a value with `includes()`
The `includes()` function tests if the passed item exists inside the array. It returns a boolean value.
```js
// given our data
const pets = ["cat", "dog", "bat"];
// functional way
const found = pets.includes("dog");
// iterative way
let found = false;
pets.forEach((pet) => {
if (pet === "dog") {
found = true;
}
});
// or most of the time done with indexOf
const found = pets.indexOf("dog") >= 0;
console.log(found); // outputs true
```
@@ -0,0 +1,170 @@
---
authors:
- "ddivad#0001"
- "veksen#1060"
created_at: "2019/10/01"
updated_at: 2020/05/20
title: Async/Await
recommended_reading:
- javascript/promises/intro
---
## Async/Await
Async/Await is another way to handle the calling of asynchronous code and is built on top of Promises. It makes it possible to write asynchronous code that feels synchronous.
**Its usage is equivalent to resolving a promise with `.then()`**.
It is made up of 2 keywords as the name suggests: `async` and `await`. These need to be used together for this method to work.
## Async
The `async` keyword is used to show that the function is going to return a promise. **Any return values from the function will be converted to a promise automatically**, if they are not already.
```js
async function getWeather() {
return "sunny";
}
getPromise();
// Promise<"sunny">
```
This basic example will return a promise with the value of `getWeather`.
## Await
The `await` keyword is used to wait until a promise has executed and fetches the result. In order to use the `await` keyword, you **need** to be inside an `async` function.
```js
async function checkWeather() {
const weather = await getWeather();
console.log(weather); // "sunny"
}
```
This code will call the `getWeather()` function from above and will wait on that line until the promise returned from the `async` function has returned.
Another example to demonstrate this is if we extended the `getWeather()` function from above to add a 5 second delay.
```js
async function getWeather() {
const promise = new Promise((resolve, reject) => {
setTimeout(() => resolve("sunny"), 5000);
});
const weather = await promise; // Execution waits here until promise resolves
console.log(weather); // "sunny"
}
```
## Error Handling
As with Promises, if the Promise returns with an error, it will affect the `await` call that triggered it. When using Promises without Async / Await, the `.catch()` syntax is used, and this also exists with Aysnc / Await using the `try...catch` syntax. This can be demonstrated by making our `foo()` function throw an error.
```js
async function foo() {
throw new Error("An Error Occurred");
}
```
This would be handled using Aysnc / Await like so:
```js
async function getData() {
try {
let data = await foo();
console.log(data);
} catch (err) {
console.error(err); // err: An Error Occurred
}
}
```
## Beginner Mistakes
As mentioned in the [intro](./intro.md), Promises are the highest source of confusion for beginners. Async / Await adds another layer on top of Promises, and comes with its own pitfalls.
`await` will **only** work if the function you try to add `await` to is `async`. Using `await` in top level code will not work (yet).
```js
let weather = await getWeather(); // syntax error
```
To get around this issue, you can use an declare asynchronous function anonymously, if needed:
```js
(async () => {
let weather = await getWeather();
console.log(weather); // "sunny"
})();
```
Top-Level-Await is something that _may_ get added to Javascript in the future, but for now wrapper functions like above are needed for this functionality.
## 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
async function getCharacters() {
const response = await fetch(`https://rickandmortyapi.com/api/character`);
const data = await response.json();
return data.results;
}
// or, mixed
async function getCharacters() {
const data = await fetch(
`https://rickandmortyapi.com/api/character`
).then((res) => res.json());
return data.results;
}
(async () => {
try {
let characters = await getCharacters();
console.log(characters); // (20) [{...}, {...}, {...}]
} catch (err) {
console.error(err);
}
})();
```
In this example, we are querying real data from the Rick & Morty API. This API has a lot of information regarding Rick & Morty, but here, we are trying to retrieve all the characters.
- The first thing we do is use `fetch` to retrieve the data from the API. `fetch` is a built in function in web browsers to do http requests, and returns a Promise by default. We `await` the result of this.
- When we get the result, we need to get the `JSON` value of the data. To do this, the `.json()` method from fetch is used. We then return the results.
- As `await` can only be used in an `async` function, we use the method from above to make this work. As `getCharacters()` returns a Promise due to it being `async`, we `await` the result. We surround this in a `try...catch` in case fetch returns an error. Then, if no error is returned, `characters` contains the information we want, and is logged to the console. If `getCharacters()` returns an error, that error is also logged.
### Let's also look at an example from Discord.js:
```js
client.on("message", (msg) => {
if (msg.author.bot) return;
if (msg.content === "ping") {
const message = await msg.channel.send("pong");
message.react("⚠️");
}
})
```
## Comparision with default Promises
Below is the same code implemented without using Async / Await as a comparision. Here, you can see the differences between the two methods, and how Aysnc / Await makes the code appear in a _more synchronous_ pattern, and can be clearer to follow.
```js
function getCharacters() {
return fetch(`https://rickandmortyapi.com/api/character`)
.then((res) => res.json())
.then((res) => res.results);
}
getCharacters()
.then((characters) => {
console.log(characters); // (20) [{...}, {...}, {...}]
})
.catch((err) => console.error(err));
```
@@ -0,0 +1,63 @@
---
authors:
- "veksen#1060"
created_at: "2020/05/20"
title: Converting a callback
recommended_reading:
- javascript/promises/intro
- javascript/promises/async-await
---
It's still pretty common to be forced to use an API that doesn't support promises. While a promise API is often preferred, it's not always available.
Before anything check:
- If your library might support both callbacks and API, in the documentation, or README from Github
- If there is not another library that does the same thing, but supports promises.
## From a callback
Let's look at a conventional, but fictional callback API:
```js
getWeather("Los Angeles", (error, result) => {
if (err) throw err;
console.log(result); // "sunny"
});
```
## To a promise
If we want to use it as a promise, we'll need to wrap a promise around it:
```js
function getWeatherAsync(city) {
return new Promise((resolve, reject) => {
getWeather(city, (error, result) => {
if (err) reject(err);
resolve(result);
});
});
}
```
Which we can now use:
```js
getWeatherAsync("Los Angeles")
.then((weather) => {
console.log(weather);
})
.catch((error) => {
console.log(error);
});
// or using async/await
const weather = await getWeatherAsync("Los Angeles").catch((error) => {
console.log(error);
});
console.log(weather);
```
@@ -0,0 +1,112 @@
---
authors:
- "Xetera#0001"
- "veksen#1060"
created_at: 2019/07/26
updated_at: 2020/05/20
title: Introduction to Promises
recommended_reading:
- javascript/callbacks/intro
- 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
});
```
Outlining this one again, because it's very common, is to attempt to use the value of a promise, but not resolving it:
```js
// Incorrect code, don't copy!
const weather = getWeather("Los Angeles");
console.log(weather); // Promise {<pending>}
```
## 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) [{...}, {...}, {...}]
});
```
@@ -0,0 +1,72 @@
---
authors:
- "Xetera#0001"
created_at: "2019/07/26"
title: Simplifying Promises
---
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 to 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,120 @@
---
authors:
- "Aiden#8627"
title: "Spread operator"
created_at: 2019/08/10
external_resources:
- text: MDN Spread Operator
href: "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax"
- text: Javascript.info Spread/rest
href: "https://javascript.info/rest-parameters-spread-operator"
- text: Freecodecamp.org Spread/rest
href: "https://www.freecodecamp.org/news/spread-operator-and-rest-parameter-in-javascript-es6-4416a9f47e5e/"
---
Spread operator (or spread syntax) is a powerful feature in Javascript which allows you to do such things as merging or copying objects, expanding an array into function arguments and a lot more. In this post, we are going to cover most of its use-cases.
## Copying an object
In Javascript, every primitive is copied when passed around. However, objects (arrays are also objects), gets their reference copied. Which means that if you're modifying an object, the original one is modified too. For example:
```js
const a = { x: 5 };
const b = a;
b.x = 10;
console.log(a.x); // 10
```
Sometimes this is not what you want as it can introduce nasty side-effects. Thankfully, you can copy an object easily with spread operator:
```js
const a = { x: 5 };
const b = { ...a };
b.x = 10;
console.log(a.x); // 5 - Not modified!
console.log(b.x); // 10
```
You can also do it with arrays:
```js
const a = [1, 2];
const b = [...a];
b[0] = 10;
console.log(a[0]); // 1 - Not modified!
console.log(b[0]); // 10
```
> Note: This is just a shallow copy, which means that if you have nested objects, they won't get copied!
## Merging objects
Spread operator also allows you to merge objects:
```js
const a = { x: 5 };
const b = { y: 10 };
console.log({ ...a, ...b }); // { x: 5, y: 10 } - Merged!
```
With arrays:
```js
const a = [1, 2];
const b = [3, 4];
console.log([...a, ...b]); // [1, 2, 3, 4] - Merged!
```
Here's a real-world example. Imagine that you're making a function which accepts an `options` object as argument, but you also want to have default values for this object. Here's a not so good way to do it without spread operator:
```js
const f = (opts) => {
const options = {};
options.foo = opts.foo || "default value";
options.bar = opts.bar || "default value";
options.x = opts.x || 10;
// ...
};
```
This works, but here's a better way:
```js
const f = (opts) => {
const defaults = {
foo: "default value",
bar: "default value",
x: 10,
};
const options = { ...defaults, ...opts };
// ...
};
```
## Expanding an array as function arguments
Spread operator also allows you to expand an array as function arguments. Each element of the array will be an argument of the function. For example:
```js
const numbers = [2, 4, 8, 10, 11, 14];
console.log(Math.max(...numbers)); // 14
```
The array gets expanded like so: `Math.max(2, 4, 8, 10, 11, 14)`
## Variadic functions
A variadic function is a function which accepts an arbitrary amount of arguments (called rest parameters in Javascript). For example:
```js
const f = (...args) => {
console.log(args);
};
f(1, 2, 3, 5); // [1, 2, 3, 5]
```
As you can see, you can call the function with an infinite number of arguments and it will receive them as an array. Keep in mind that rest parameters must always be at the end.
@@ -0,0 +1,203 @@
---
authors:
- "ddivad#0001"
created_at: "2019/10/06"
title: Variables
---
A `variable` in Javascript is a "named container" that can hold data. Variables are declared by giving them a name and a value - the `name` allows you to reference the variable throughout your program, and the `value` is the current value the variable represents.
Variables can be defined in the following ways:
Initialized without a starting value:
```js
let myVar;
```
Initialized with a value:
```js
let myVar = "Hello World";
```
Initialized with a value and redefined:
```js
let myVar = "Hello World";
console.log(myVar); // variable is used by referencing value with 'let'
myVar = "New value";
console.log(myVar);
```
## Dynamic Types
Variables in Javascript do not have explicit types, as some other languages (eg: Java) do. This means that when declaring a variable, you only use `name = value`, and don't need to add a type as well. The type is automatically chosen based on the value.
```js
let myString = "Hello";
let myBoolean = true; // false is also valid
let myNumber = 1;
let myFloat = 1.0;
```
## Let vs Const
Javascript has two "types" of variable declaration: `let` and `const`. These behave in largely the same way, with **one important difference**:
- Let: the value of variables using `let` can be changed throughout the course of your program.
- Const: the value of variables using `const` cannot be changed after they are defined.
```js
let myVar = "Hello World";
myVar = "New Value!"; // This is ok, and myVar's value will be changed.
const myVar2 = "Hello World";
myVar2 = "New Value!"; // This will fail, as myVar2 has already been defined.
```
If the value of the variable will only ever have one value, `const` should be used to define it. This is safer, as if you try to re-assign it somewhere else you will get an error, instead of having unexpected behaviour by accidentally overwriting the value.
If the value of the variable needs to change throughout the course of a program (user input, calculations, etc...), `let` should be used to define it.
### Const Quirks:
The `const` declaration in Javascript allows you to create a variable that cannot be redeclared after it has been declared initially. This is similar to a lot of other languages.
However, in Javascript, there is an edge case to be aware of when using objects and arrays.
```js
const myArray = [1, 2, 3];
console.log(myArray); // [1,2,3]
myArray.push(4);
myArray.push(5);
console.log(myArray); // [1,2,3,4,5]
const myObj = { foo: "bar" };
console.log(myObj); // {foo: bar}
myObj.foo = "re-assigned";
console.log(myObj); // {foo: re-assigned}
```
This, however, will still not work:
```js
const myArray = [1, 2, 3];
myArray = [1, 2, 3, 4, 5]; // Error: myArray has already been defined
```
## What about var?
As well as using `let` or `const` to define variables, there is a 3rd way that exists using `var`. Var is from older versions of Javascript from before let and const were introduced. Nowadays, using `let` or `const` is recommended over `var`.
There are a number of problems that come from using `var` to declare variables, that are fixed by using `let` or `const` instead.
### Block & Function Scoping
Var is not "block scoped" (a block is anything that contains `{}`, so functions, if, for loop, etc...) This means that variables declared using `var` are not _just_ defined in the block they are declared, but declared and can be accessible globally. This can have un-intended side effects.
```js
for (var i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); // 5 as i is a 'global' variable
if (true) {
var myVar = "test";
}
console.log(myVar); // 'test'
```
This is fixed using `let`
```js
for (let i = 0; i < 5; i++) {
console.log(i);
}
console.log(i); // Error: i is undefined
if (true) {
let myVar = "test";
}
console.log(myVar); // Error: myVar is undefined
```
However, if the above code was in a function, this would not be the case. In the case of a function, the variable will be scoped to the given function, and not accessible outside it. Eg:
```js
function myFunction() {
var myVar = "test";
}
console.log(myVar); // Error: test is undefined
```
This can cause confusing behaviour, as `var` has different scoping behaviour depending on if its in a function or not. This is solved by using `let` or `const`.
### Hoisting
Variables defined using `var` are also hoisted to the top of the function they are declared in, which can cause some weird behaviour.
```js
console.log(myVar); // undefined.
var myVar = "test";
```
You may have expected the output to be "ReferenceError: myVar is not defined", but instead the output is just "undefined". This is because the variable declaration is hoisted to the top of the function (global scope in this case), and essentially looks like this at runtime:
```js
var myVar;
console.log(myVar); // undefined.
myVar = "test";
```
This also happens when declaring `var` inside a function:
```js
function myFunction() {
myVar = "test";
console.log(myVar);
var myVar;
}
myFunction(); // this will work fine and log 'test'
```
The above works, because with hoisting, it is essentially the same as
```js
function myFunction() {
var myVar;
myVar = "test";
console.log(myVar);
}
myFunction();
```
This creates problems when writing code using `var`, as it means that you can try to use a variable before it was given a value.
There is also weird behaviour when it comes to declarations like
```js
var myVar = "test";
```
Variable declarations get hoisted, but the assignments don't. Going back to the previous example:
```js
console.log(myVar); // undefined.
var myVar = "test";
```
Here, the declaration is hoisted to the top of the function, but the assignment of `test` to the variable happens where is appears in the code. Eg:
```js
var myVar;
console.log(myVar); // undefined.
myVar = "test"; // assignment isn't hoisted
```
In summary, using `let` and `const` is recommended when writing modern Javascript to solve these issues. Sometimes you will see `var` in old tutorials. If you come across this, it is good practice to replace it with `let` or `const` when following the tutorial, and getting into the habit of using up-to-date practices when learning.
@@ -0,0 +1,21 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: Kotlin
---
###### About
One line language description: Kotlin is a general-purpose programming language that can run on a JVM or be transpiled to Javascript code. It can use functional, procedural, and OO paradigms, and can interleave them. Primarily developed by JetBrains.
###### Links
- [Official Website](https://www.kotlinlang.org/)
- [Official Docs](https://kotlinlang.org/docs/reference/)
- [Tutorials](https://kotlinlang.org/docs/tutorials/)
- [Mooc (not free)](https://www.udemy.com/kotlin-course/)
###### Recommended reading
- Kotlin in Action by Dmitry Jemerov and Svetlana Isakova
@@ -0,0 +1,117 @@
---
authors:
- "supergrecko#3434"
created_at: "2019/08/23"
title: "Creating C bindings with Kotlin/Native"
external_resources:
- text: KotlinLang.org C-interop reference
href: "https://kotlinlang.org/docs/reference/native/c_interop.html"
- text: Kotlin releases on GitHub
href: "https://github.com/JetBrains/kotlin-native/releases"
---
## Interoperability with C
Kotlin/Native supports interoperability with the C programming language. This article will show you how to create bindings between C and Kotlin/Native.
### Setup
This guide assumes you already have the Kotlin compiler and the GCC C compiler installed on your computer.
If you do not have the Kotlin compiler installed on your computer you can download it from the GitHub releases linked above.
### Creating our C library
We will be creating a very simple library to demonstrate linking.
This is our `App.h` file
```c
#ifndef APP_H
#define APP_H
void run();
#endif
```
And this is our `App.c` file
```c
#include <stdio.h>
#include "App.h"
void run() {
printf("Hello, from C");
}
```
### Compiling our C library
First of all we will need to compile our C sources.
```bash
gcc -c "-I$(pwd)" App.c -o App.o
```
The `"-I$(pwd)"` flag translates to the gcc -I flag with our current working directory as its parameter. You can also type out the full path if you want to.
We now have our compiled C code in `App.o`. Now we have to turn the compiled output into a static library.
We'll save our compiled static library in a file named `App.a`
```bash
ar rcs App.a App.o
```
### Compiling our bindings
Now we need to create a `App.def` file for the Kotlin cinterop tool
The minimal requirements for a `.def` file is some headers. We will include our header file here.
```def
headers = App.h
```
We will run the `cinterop` command to generate the Kotlin bindings for our C library.
```bash
cinterop -def App.def -compilerOpts "-I$(pwd)" -o App.klib
```
We're now ready to create a Kotlin file to interact with our C library so let's do that. Let's name this file `App.kt`
```kotlin
import App.run
fun main() {
println("Hello, from Kotlin/Native")
run()
}
```
We'll print out a hello from Kotlin, and then the hello from C.
### Executing our Kotlin
There is only one more step before we can run our Kotlin application, we need to compile our Kotlin, so let's do that.
Using the konanc compiler we will bundle our C library with our Kotlin file.
```bash
konanc -l App.klib App.kt -linker-options App.a -o App.kexe
```
We can now run our executable so let's do that.
```bash
./App.kexe
```
This should be the program output:
```text
Hello, from Kotlin/Native
Hello, from C
```
@@ -0,0 +1,110 @@
---
authors:
- "supergrecko#3434"
created_at: "2019/07/27"
title: Singletons
external_resources:
- text: Wikipedia.org Singleton Pattern
href: https://en.wikipedia.org/wiki/Singleton_pattern
- text: phpenthusiast.com Singleton Pattern
href: https://phpenthusiast.com/blog/the-singleton-design-pattern-in-php
- text: phptherightway.com Singleton Pattern
href: https://phptherightway.com/pages/Design-Patterns.html#singleton
- text: php.net Static Keyword
href: https://www.php.net/manual/en/language.oop5.static.php
- text: php.net Late Static Bindings
href: https://www.php.net/manual/en/language.oop5.late-static-bindings.php
- text: Wikipedia.org Static Keyword
href: https://en.wikipedia.org/wiki/Static_(keyword)
- text: Wikipedia.org Null Coalescing Operator
href: https://en.wikipedia.org/wiki/Null_coalescing_operator
- text: php.net Null coalescing operator
href: https://www.php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op
---
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)
```
@@ -0,0 +1,19 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: PHP
---
###### Useful links and documentation
- [Official documentation](https://secure.php.net/manual/en/)
- [Laracasts PHP tutorials](http://laracasts.com/)
- [PHP: The Right Way](https://phptherightway.com/)
- [PHP Standard Recommendations](https://www.php-fig.org/psr/)
- [OWASP Cheatsheet](https://cheatsheetseries.owasp.org/)
###### Useful Libraries
- [Composer package manager](https://getcomposer.org/)
- [phpDocumentor](https://www.phpdoc.org/)
@@ -0,0 +1,120 @@
---
authors:
- "supergrecko#3434"
created_at: "2019/08/07"
title: Prepared Statements
external_resources:
- text: php.net The PDOStatement class
href: https://www.php.net/manual/en/class.pdostatement.php
- text: phptherightway.com PDO Extension
href: https://phptherightway.com/#pdo_extension
---
The PDO driver supports prepared statements. A prepared statement is a template statement with placeholders which can be executed with real values. Prepared Statements are also essential for avoiding SQL-injection attacks.
A prepared statement is safe because we're executing the statement in two phases, first we send the template to the server, with the placeholder values, and then we send the values.
# What is SQL injection?
SQL injection is the act of modifying a query by inserting code which would modify the SQL query.
In a traditional SQL injection attack the user will pass a piece of malicious code which will change the SQL query being ran.
Let's say we have this PHP snippet to execute a query.
```php
$sql = "SELECT * FROM `users` WHERE `age` > {$_POST['age']};";
$pdo->query($sql);
```
This would run as expected if we get a regular input, like `20` from our request body, but if we'd get `20 OR 1 = 1; DROP TABLE users` then we would end up with a final query which looks like this:
```sql
SELECT * FROM `users` WHERE `age` > 20 OR 1 = 1; DROP TABLE users;
```
This would fetch every single row from the `users` table as `1 = 1` will always evaluate to true and then drop the entire table which would break your entire application.
# How does a Prepared Statement prevent SQL injection?
You can think of a prepared statement as a conversation between the user and the database. A basic prepared statement would look a little like this:
> User: Hello Database, I'm going to run this prepared statement. I will tell you what it should look like, but I won't give you any values. Here's my query:
```sql
SELECT * FROM `users` WHERE `age` > :age;
```
> Database: Okay I have received the query, so I'll be selecting everything from users where age is more than `:age`. Now you can send me the value for `:age` and I'll execute it.
> User: Here's the value for `:age`, it's the number `18`.
> Database: Okay, here are all the results where age was more than 18.
Via a prepared statement we tell the database what our query will look like, then we pass the values. This means there is no way of modifying the SQL query and you'll probably just get a goofy result instead of having your entire database dropped.
# Creating a Prepared Statement
There are three steps to executing a prepared statement:
- Preparation
- Binding
- Execution
## Preparation
First of all we need to create a SQL query which we want to execute. Let's say we're going to add a new entry to a table named `users`. We'll create this SQL query:
```sql
INSERT INTO `users` (username, email) VALUES (:username, :email);
```
The `:<string>` values are the placeholder values we're going to bind.
Let's create the prepared statement in PHP:
```php
// Assume that $pdo is a PDO connection
$statement = $pdo->prepare("INSERT INTO `users` (username, email) VALUES (:username, :email);");
```
We now have a variable `$statement`. This variable is an instance of `\PDOStatement` which is linked in th external resources.
## Binding
We're now ready to bind a set of values to our `$statement` variable. This is done with the `\PDOStatement::bindParam` method. For this example we will set `:username` to `"Joe"` and `:age` to `25`.
A simplified version of the `bindParam` signature looks a little like this:
```php
PDOStatement::bindParam($parameter, $value, $type)
```
- `$parameter`: The placeholder parameter we're going to bind
- `$value`: The value we're going to insert
- `$type`: The data type we're going to bind. [Valid values](https://www.php.net/manual/en/pdo.constants.php)
Let's bind our values to our prepared statement
```php
$statement->bindParam(":username", "Joe", PDO::PARAM_STR);
$statement->bindParam(":age", 25, PDO::PARAM_INT);
```
We've now told the statement that `:username` is a string with the value `"Joe"` and that `:age` is an integer with the value `25`.
# Execution
Executing the prepared statement is very simple, it's a single function call, `\PDOStatement::execute`.
Let's execute our SQL statement.
```php
$statement->execute();
```
If you're looking to capture the result you can always do
```php
$result = $statement->execute();
```
@@ -0,0 +1,35 @@
---
authors:
- "veksen#1565"
created_at: 2019/12/15
title: Python
---
###### Beginner
- [Official tutorial](https://docs.python.org/3/tutorial/)
- [Automate the boring stuff](https://automatetheboringstuff.com/)
- [Beginner's guide](https://wiki.python.org/moin/BeginnersGuide/NonProgrammers)
###### Documentation
- [https://docs.python.org/3/](https://docs.python.org/3/)
- [https://www.python.org/dev/](https://www.python.org/dev/)
###### Video
- [Socratica](https://goo.gl/8xKVKE)
- [thenewboston](https://goo.gl/9EqF2J)
###### Books
- [Free](https://goo.gl/Lxhp7i)
- [Python Crash Course - paid](https://goo.gl/XQ7Nx6)
- [Advanced - paid](https://wiki.python.org/moin/AdvancedBooks)
###### Other
- [TalkPython | Podcast](https://goo.gl/xwieUA)
- [Exercises](http://www.practicepython.org/)
- [List Comprehensions](https://www.programiz.com/python-programming/list-comprehension)
- [More Resources](https://goo.gl/Lw3Vqi)
@@ -0,0 +1,211 @@
---
authors:
- "T0M#5956"
created_at: 2019/11/14
updated_at: 2019/11/14
title: Basic Python Operators
---
## Python Operators
Python has 7 categories of operators: Arithmetic, assignment, comparison, logical, identity, membership and bitwise operators. In this article I will cover some of the operators seen most commonly in Python programming - arithmetic, assignment and comparison. Note: this article covers Python 3 and there have been alterations and additions of operators since Python 2, so some elements of this article may only apply to Python 3.
## Arithmetic Operators
Arithmetic operators are used in conjunction with numeric values in order to perform basic mathematical operations.
### Addition Operator - `+`
The addition operator is used to add two numeric values (can be hex, integers or floats), returning a base 10 number and can also be used to concatenate certain data types.
```python
1 + 4 # equals 5
1.1 + 1.1 # equals 2.2
0x100 + 0x100 # 512
'hello'+' '+'word' # equals hello world
[1,3]+[2] # equals [1,3,2]
(1,1)+(2,2) # equals (1,1,2,2)
```
### Subtraction Operator - `-`
The subtraction operator is used to subtract two numeric values, subtracting the value on the left hand side operand from the operand on the right hand side (can be hex, integers or floats), returning a base 10 number.
```python
8 - 4 # equals 4
1.4 - 1.1 # equals 0.3
0x200 - 0x100 # 256
```
### Division Operator - `/`
The division operator is used to divide two numeric values, dividing the value on the left hand side by the one on the right hand side (can be hex, integers or floats), returning a base 10 number float.
```python
8 / 2 # equals 4.0
8 / 3 # 2.6666666666666665
10 / 1.1 # equals 9.09090909090909
0x200 / 0x10 # 32.0
```
### Division Operator - `/`
The division operator is used to divide two numeric values, dividing the operand on the left hand side by the operand on the right hand side (can be hex, integers or floats), returning a base 10 number float.
```python
8 / 2 # equals 4.0
8 / 3 # 2.6666666666666665
0x200 / 0x10 # 32.0
```
### Modulus Operator - `%`
The modulus operator is used to divide two numeric values, dividing the operand on the left hand side by the operand on the right hand side (can be hex, integers or floats), and returning the remainder as a base 10 number.
```python
8 % 3 # equals 2
0x232 % 0xA # equals 2
1.1 % 0.3 # equals 0.2
```
### Power Operator - `**`
The power operator is used find the result of the left hand operand to the power of the right hand operand, returning a base 10 number. Either value can be a hex number, and integer or a float.
```python
4 ** 10 # equals 1048576
0x10 ** 0x4 # equals 65536
1.1 ** 4.4 # equals 1.5209950991358059
```
### Floor Division - `//`
The floor division operator is used to find the result of the left hand operand divided by the right hand operand, rounded down to the nearest integer. Either value can be a hex number, and integer or a float. In floor division, `a // b` is the same as `int(a/b)`.
```python
5 // 2 # equals 2 - same as int(5/2)
0x100 // 0xA # equals 25
5.6 // 1.1 # equals 5
```
## Assignment Operators
### Assign Operator - `=`
Assigns right hand value to the left hand operand. Literals (such as integers and floats) cannot be assigned. The right hand value can be a large number of values such as literals and variables.
```python
a = 3 # variable a is now equal to 3
b = 4 * 2 # variable b is now equal to 8
c = b * 2 # variable c is now equal to value of variable b multiplied by 2, in this case c becomes 16
```
### Assign Operator and an Assignment Operator - e.g. `-=`
You can use the assign operator in conjunction with any of the above arithmetic operators using the syntax `operand {assignment operator}= operand`, such as `a //= 9`. This performs the relevant arithmetic operation on the two operands and then assigns the result to the left operand. In all below demonstrations, variable `a` starts equal to 10.
```python
a += 1 # a becomes 11
a -= 1 # a becomes 9
a *= 2 # a becomes 20
a /= 2 # a becomes 5
a %= 3 # a becomes 1
a **= 2 # a becomes 100
a //= 3 # a becomes 3
```
## Comparison Operators
### Equals Operator - `==`
Compares the two operands on either side of the operator, returning `True` if they are equal and `False` otherwise. Strict type comparison - a string version of `'8'` doesn't equal the integer `8`, therefore this operators acts as an identical operator.
```python
8 == 4 + 4 # equals True
a == a # equals True
9 == 3 + 5 # equals False
'8' == 8 # equals False
'hello' == 'hello' # equals True
[1,2] == [1,2] # equals True
```
### Not Equal Operator - `!=`
Compares the two operands on either side of the operator, returning `True` if they are not equal and `False` if they are equal. Strict type comparison, therefore this operators acts as a not identical operator.
```python
8 != 4+4 # equals False
8 != 3+3 # equals True
'8' != 8 # equals True
```
### Greater Than Operator - `>`
Checks whether the left hand operand is numerically larger than the right hand operand, returning `True` if it is and `False` otherwise. This operand can compare other data types, but always returns `False`.
```python
8 > 7 # returns True
7 > 7 # returns False
6 > 7 # returns False
'9' > '8' # returns False
'7' > '8' # returns False
```
### Lesser Than Operator - `<`
Checks whether the left hand operand is numerically smaller than the right hand operand, returning `True` if it is and `False` otherwise. This operand can compare other data types, but always returns `False`.
```python
7 < 9 # returns True
8 < 8 # returns False
9 < 9 # returns False
'9' < '10' # returns False
'7' < '6' # returns False
```
### Lesser/Greater or Equals Operator - `<=` or `>=`
Behaves similarly to their respective lesser/greater operators however also returns `True` if the left side and right side operands are the same. If non-numerical data types are used, this operator only returns `True` when the operands are identical.
```python
7 <= 7 # returns True
7 >= 7 # returns True
9 >= 8 # returns True
8 <= 9 # returns True
9 >= 10 # returns False
```
## Operators Precedence
Python operators are performed in the following order, with the highest operators on the list being performed before the lower operators. If the operators are on the same row on the list (meaning they have the same levels of precedence), the operators are performed with the reading left to right on the line of code.
- `**`
- `~`, `+`, `-`
- `*`, `/`, `%`, `//`
- `+`, `-`
- `>>`, `<<`
- `&`
- `^`, `|`
- `<=`, `<`, `>`, `>=`
- `==`, `!=`
- `=`, `%=`, `/=`, `//=`, `-=`, `+=`,`*=`, `**=`
- `is`, `is not`
- `in`, `not in`
- `not`, `or`, `and`
### Example of Operator Precendence
If you wanted to execute the line of code `2 ** 2 * 4 / 2` in Python, the code would be executed like so. First, the power (`**`) operator would be executed first as it is the most precedent and therefore takes highest priority, this makes the line of code equal to:
```python
2 ** 2 * 4 / 2
4 * 4 / 2
```
Next, due to the multiplication `*` and division `/` operators having the same precedent, they are executed left to right, with the multiplication operator first and then the division operator because that is the order they appear left to right in the line of code, meaning the code would be executed as following:
```python
4 * 4 / 2
16 / 2
8
```