RSS

Tag Archives: programming

ECMAScript 2015 Destructuring and Spread

Destructuring

Destructuring is a way to unpack values from arrays, or properties from objects, into its own variables.

var o = {p: 42, q: true};
var {p: foo, q: bar} = o;

console.log(foo); // 42
console.log(bar); // true

Spread

Spread allows collection to be expanded in places where zero or more arguments are expected (in function), or elements are expected (in array literals), or key-value pairs are expected (in object literals).

function sum(x, y, z) {
  return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers));
// expected output: 6

console.log(sum.apply(null, numbers));
// expected output: 6

Reference

 

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Advertisements
 
Leave a comment

Posted by on January 10, 2019 in General, References

 

Tags: , , , , ,

Memoization, huh?

Memoization

To put it simply, it’s caching. In a fancy term.

Memoization is usually being used in function. In other words, memoization is caching in the scope of Function. The purpose of memoization is to avoid doing computation that’s needed to be done repeatedly. This essentially to save time and resources.

The way functions achieve memoization is by caching the result and returning the result if it has been computed previously.

Couple use cases of memoization

  • Pure functions that require intensive computation and called repeatedly.
  • Pure and recursive Function.

See Fibonacci example in the link reference.

Reference

https://medium.com/@chialunwu/wtf-is-memoization-a2979594fb2a

 
Leave a comment

Posted by on January 4, 2019 in General

 

Tags: , ,

NgRx Entity

NgRx Entity

NgRx Entity is a library to handle entity within NgRx framework. The entity in the context is defined as the application’s domain objects, like User, Employee, etc.

The purposes of NgRx Entity are basically:

  • Reduce boilerplate code.
  • Search and sort entities quickly.

The first thing we need to use NgRx Entity is to create an entity adapter, like so:

const adapter = createEntityAdapter();

NgRx Entity also defines `EntityState<>` interface. The interface is also extensible should the additional properties in the application state are needed,

The shape of EntityState is something like this:

interface EntityState {
  ids: string[];
  entities: { [id: string]: V };
}

What this allows us to do is:

  • Find entity quickly using `entities` dictionary.
  • Maintain order of the list, good for use in sorting.

Some boilerplate codes that are reduced when using NgRx Entity:

  • No need to specify properties of the state interface.
  • Add, remove, update of entities in the state are handled by entity adapter.
  • Entity adapter has most commonly used selectors.

Reference

https://medium.com/ngrx/introducing-ngrx-entity-598176456e15

 
Leave a comment

Posted by on December 20, 2018 in General, References

 

Tags: , , , , ,

NgRx State Selectors

NgRx State Selectors

As our application grows, the data structure that represents the application states could get more complex. State data structure in ngRx is tree-like and in the early development, the structure may only have few properties. As the application grows, the structure could have deep nested objects.

When states have deep nested objects, we will have to write more code to select the slice of state. Something like:

// Complex data structure
let state = {
    products: {
        pizza: {
            name: "Pepperoni",
            amount: 4
        },
        topping: {
            name: "mushroom",
            amount: 3
        }
    }
};

// Selecting pizza state
let pizza = state.products.pizza;

Selecting pizza state requires dot notation and it’s also prone to error where products is undefined, that line of code will blow up.

Another issue with this is that we will have to write the same line of code to get pizza state every where we need the state.

This is where state selectors in ngRx comes in. It allows us to define selectors for our states and use it everywhere in our application.

There are mainly 2 state selectors, createFeatureSelector and createSelector. The first one mainly deals with state at the root level while the second one can be used to select a specific object in the state (for example, pizza or topping).

Reference

https://toddmotto.com/ngrx-store-understanding-state-selectors

 
Leave a comment

Posted by on December 12, 2018 in General

 

Tags: , , , , ,

NgRx Store Explained

NgRx Store

ngRx Store is a library for Angular 2+, its function is almost like event bus where the store is a central storage for all events and whenever an event is added, the store emits an action. Whoever subscribe to the store‘s action will then get notified. Very similar to pub-sub pattern.

The purpose of ngRx Store is to simplify the state management, that sometime can be simple at first but, as the application grows, becomes unimaginably complicated.

Some example usage of ngRx Store that I can think right now are:

  • Forward execution. When an Angular application sends an API call to update, let’s say, employee data, it doesn’t need to call API anymore to query what the current employee data is. However, things get complicated when there’s a certain logic needs to be applied when updating employee data. For example, when the hire date is set to the future, the employee status will also need to be changed. ngRx Store can be used to manage the employee state so that it remains consistent at every part of the application.
  • Reduce extraneous props. Extraneous prop is when we have a deep component tree and have to pass object around to the leaf component. ngRx Store eliminates the need of passing the object around and just have the leaf component subscribe to the `store` to receive the action. A concrete example of this is notification counter. The counter is normally in its own component and every other event can increase the count. By using ngRx Store, we can avoid other components passing the count to the counter component.
  • Sort of the similar to extraneous props, we can have 2, or more, components that use the same data but display it differently. With ngRx Store, we can manage the state of the data in one place and all other components that use the data just subscribe to it.
  • Step-by-step, wizard-y workflow. Think of this like your tax filing software where it asks you questions and, depend on your answer, take you to different workflow. In Angular, each step the users take can use a separate component and ngRx Store can be used to maintain the state of the whole workflow process.

The problem that ngRx Store trying to solve is really similar to challenges that a large scale enterprise application faces, it just does it in a smaller scale, UI front-end in this case.

There’s definitely a lot more to this concept than what I cover here, but hopefully this gives you the gist of how it works at the high level. There are lots of resources online that cover this very topic.

 
Leave a comment

Posted by on December 1, 2018 in General

 

Tags: , , , , ,

BuzzWord: Functional Programming Short Guides

This is summary of: Anjana Vakil’s video

1. Do everything with functions. Function take input and return output.
Non functional

var name = “Anjana”;
var greeting = “Hi, I’m ”;
console.log(greeting + name);
// Output: “Hi, I’m Anjana”

Functional

function greet(name) {
    return “Hi, I’m ” + name;
}
greet(“Anjana”);
// Output: “Hi, I’m Anjana”

2. Avoid side effects. Function should only process input it is given and return output, everything else is distractions (ie: process global variables, run command not intended to process input, etc). This is pure functions.
Not pure

var name = “Anjana”;
function greet() {
    console.log(“Hi, I’m ” + name);
}

Pure

function greet(name) {
    return “Hi, I’m ” + name;
}

3. Could have higher-order functions. Inputs and outputs can be functions.

function makeAdjectifier(adjective) {
    return function (string) {
        return adjective + “ ” + string;
    };
}

var coolifier = makeAdjectifier(“cool”);
coolifier(“conference”);
// Output: "cool conference"

4. Don’t iterate. Instead of iterate, use functions (map, reduce, filter).
Iterate

var fruits = ["apple", "orange", "banana"];
var goodFruits = [];
for (var i = 0; i  fruit + " great");
// Output: ["apple great", "orange great", "banana great"]

5. Avoid mutability objects. Unintended changes to objects could cause confusion and introduce bugs. Instead, use immutable objects.
Mutable

var rooms = [“H1”, “H2”, “H3”];
rooms[2] = “H4”;
// Output: ["H1", "H2", "H4"]

Immutable objects with function

var rooms = [“H1”, “H2”, “H3”];
var newRooms = rooms.map(function (rm) {
    if (rm == “H3”) {
        return “H4”;
    } else {
        return rm;
    }
});
// Output: rooms => ["H1", "H2", "H3"]
// Output: newRooms => ["H1", "H2", "H4"]

6. Persistent data structure for efficient immutability.
Instead of copying immutable objects which take time and memory (space) for every single copy, use persistent data structure that treat object as nodes and connect them in tree structure, changes of objects will only affect certain nodes, not entire object. This can be achieved with third party framework such as Mori or Immutable.js

 
Leave a comment

Posted by on November 27, 2018 in General

 

Tags: , , , ,

 
%d bloggers like this: