Category Archives: javascript

Mapped Types (typescript)

ref – https://www.typescriptlang.org/docs/handbook/2/mapped-types.html

declare a type called AllAreBooleanProperties that takes in a type object called Type.
Then for every property in object Type, declare it to be boolean.

Example usage, say we have an object type that has properties type () => void:

now we use our AllAreBooleanProperties type generator and create a type that says all properties must be boolean:

Thus creating a type that forces object type to have all boolean properties.

Cloning Array the Right Way

ref – https://www.samanthaming.com/tidbits/92-6-use-cases-of-spread-with-array/

We want to clone an array, where changing a value in the new array does not affect the original array

original: [‘zero’, ‘one’]
newArray: [‘zero’, ‘one’]

So if we did this correctly, our original array shouldn’t be affected if we changed the newArray. Alright, let’s give this a try πŸ’ͺ

newArray is now: [‘zero’, ‘πŸ’©’]

original: [‘zero’, ‘one’] Great! original array is NOT affected

Using it in React’s Reducer

In React’s reducers, when we change property data of an array, React only does a value comparison of the object. If the two objects are different, it will update the DOM. If they stay the same, it doesn’t.

This works well for primitive values.

  • Are the two value’s Type same? √ string
  • Are the two values same? X one is richard, other is ricky

Update the DOM!!

But for objects it doesn’t work.

React literally does this: a === a

  • Are the two object’s Type same? √ Array
  • Are the two object’s values (in this case, address of the object) same? √

no change, no update of DOM. This is not what we want because we want the DOM to update so that we see age is 41, not 25.

No matter how much you change the object’s data, it will always stay the same if you do value comparisons.

In order to remedy this, we need to clone the array using spread syntax so that we get a new Array object (with its own address value) like so:

Now, React will do this:

  • Are the two object’s Type is Array? √
  • Are the two object’s address value same? X

Update the DOM!!!!

And this is exactly what we want.

Creating an iterator (js)

constructor, count:6


output:
6, 5, 4, 3, 2, 1

yield function vs yield result that reference function

Note we yield the result reference to JCcall()

Note that we now move yield to JCcall instead.

Another example is that we return another generator (* function) inside of our original generator function.
The yield* expression ( as opposed to the yield of a normal function above ) is used to delegate to another generator or iterable object.

The key point here is that we must put yield* in front like this:

Now, let’s run our generator.

binary loop search

We use a loop to do binary search on a sorted array.

We start with two markers, one on each end: start and end.
We then calculate mid. We compare the value at index mid to the value we’re trying to insert.

If our to insert value is larger, we move our start to mid + 1.
If our to insert value is smaller, we move our end to mid – 1.

This way, we squeeze our start and end markers tighter and tighter.

Once we squeeze where start <= end is false (AKA start > end )…our mid is at the correct index. All we need to do is see if our to insert value is larger or smaller than the value at index mid.

If larger, arr.splice(mid+1, 0)
If smaller, arr.splice(mid, 0)

Because by default splice at an index will add the value at that index and push everything down.

Memory leaks

  • https://felixgerschau.com/javascript-memory-management/
  • https://felixgerschau.com/javascript-event-loop-call-stack/
  • https://blog.sessionstack.com/how-javascript-works-memory-management-how-to-handle-4-common-memory-leaks-3f28b94cfbec

Classes in typescript

If we want Car to have different drive, simply redefine:

Modifiers

public, private, protected – Restrict access

public – can be called any where, any time
private: can be only called by other methods in THIS class.
protected – called by other methods in THIS class, or by other methods in child classes.

by default, it’s public.

If we’re ever over-riding an interface, we cannot change modifier:

If its protected, we can can access in child class.

shortcut

Also note that if we change it to private, then child classes can’t access it anymore.

In order to be made accessible in child class, we can change it back to public or protected.

Interfaces in typescript

Interface + Classes = How we get strong code reuse

Long Type Annotation

Given an object like so:

Say we want to implement a function that takes in such a type. We say, this parameter is called vehicle, and it takes in an object with property name of type string, year of type number, and whether it is broken…which is of type boolean.

Boy, this function annotation is really really long and tiring on the eyes

How to fix this long Annotation?

Creating an interface is like we are creating a type.

will tell us that we need a type like this:

now we can do this:

which is much easier on the eyes and fingers.

By definition, typescript gives us compile time checking. If we change true to 1 in oldCivic, we’ll get compile time checking for oldCivic, that it does not conform to the interface.

Functions around Interfaces

Is it important that Vehicles MUST have these properties? No, as long as Vehicle interface is a subset of what is provided in oldCivic, then we are okay.

In other words, as long as what we declared are included in the interface, then it is ok.

That is the ONLY QUESTION that is asked when we’re trying to check if the passed in object has the properties of the interface.

Let’s change the name Vehicle to Reportable. It is much more descriptive.
And change the function name.

Code Reuse with Interfaces

Notice we both have summary function that returns a string. They are both considered to be ‘Reportable’ types. So they can both be used in the parameter.

We can use a single interface to describe very different objects.

Debug typescript in Node JS

demo download

Create REST API with Typescript


mkdir Und-TSC-sec15
cd Und-TSC-sec15

Create Node Project
npm init
You’ll then have a package.json file.


You’ll then have a tsconfig.json file.

In tsconfig.json:

Now let’s install the needed modules:

standard web server independencies:
npm install –save express body-parser

development independencies:
npm install –save-dev nodemon

create src folder:
mkdir src
cd src
touch app.ts

When you are done, type tsc to compile the typescript into javascript.

Then you can debug it. Put a breakpoint there and make sure you’re on the index file. In our file, we’re on app.ts.

Once you’re on that file, go to Run > Start Debugging. You’ll see the bottom status bar turn orange. This means the server is running.

Click on View > Terminal, and you’ll see the terminal pop up. Then click on debug console. You’ll be able to see the console log from the node js app appear.

Creating Routes


cd src/routes
touch todos.ts

We extract Router from express. We can then register routes to hit functionality.
We set up the router to receive POST, GET, PATCH, and DELETE on ‘/’.
Each HTTP request will get mapped to certain functionalities that we declare in controllers/todos file.

routes/todos.ts

Finally, we need to connect our router to our server for endpoint /todos.

app.ts

Add additional routes

First, we create a class Todos so we have a structure to work with. We export a class Todo so other modules can import it, and then new it to create an instance of Todo.

Then import the class so that we get a simple data structure going.

We create functionality by implementing a function createTodo.
Note that we use RequestHandler interface, which contracts us to use
req, res, and next parameters.

controllers/todo.ts

Since it takes care of a POST request, we use parse the body property in the request
object to get the body data. The body data’s key is text.

In order do that we need to import the body-parser package in app.ts, and then extract json.
This is so that we parse the body using json.

app.ts

Open up your postman and query it like so:

class – typescript to js

ref – https://www.geeksforgeeks.org/typescript-class/

typescript

gets converted to js:

What does ‘this’ reference inside a function in an IIFE?

We have functions in IIFE, and we see that it uses this. But what does this reference?
As you can see from the example below, the ‘this’ keyword refers to the IIFE object.

> test4.bye()

“bye bye”

> test4.hello()

hello reference sayHello function. sayHello logs the ‘this’ keyword of the IIFE.
It will display the IIFE object.


Object
bye: Ζ’ sayBye()
hello: Ζ’ sayHello()
__proto__: Object
“hallo!!!ricky”

However, notice that we return a literal object. We can’t use new on the literal object because it’s not a function. So we must change this a bit in order to accomodate ‘new’.

So in our IIFE Student, we have a function constructor Student. That way when we go new Student, it would be valid because we can instantiate a function instructor.

Accessing Attributes and Functions

A class’s attributes and functions can be accessed by the object. With the help of β€˜ . ’ dot notation or bracket notation([”]) we access the data members of a class.