RSS

Tag Archives: javascript

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

Advertisements
 
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: , , , , ,

Javascript Find Unique Value in Array

Given:

var findUniq = ["f", "3", 3, "t", "f", "A"]

Find only unique value.

Solution 1 – Javascript ECMA Script 5
Check if index of the value is the first occurrence.

var uniq = findUniq.filter(function(value, index, array) {
    return array.indexOf(value) === index;
});

Solution 2 – Javascript ECMA Script 6
Short hand version of Solution 1.

let uniq = findUniq.filter((v, i, a) => a.indexOf(v) ==== i);

Solution 3 – Javascript ECMA Script 6
Using Set data type, which only allow unique value.

let uniq = [...new Set(findUniq)];

Credit:
https://stackoverflow.com/a/14438954/631631

 
Leave a comment

Posted by on August 11, 2018 in General

 

Tags: , , , , ,

JavaScript Bundle Doesn’t Work on ASP.Net MVC 5

Developers often make this very common mistake. You start an ASP.Net MVC app, add few JavaScript files and libraries, run. Everything works fine but the JavaScript.

ASP.Net MVC Bundling

public static void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                "~/Scripts/jquery-1.*"));

    bundles.Add(new ScriptBundle("~/bundles/startstop").Include(
                "~/Scripts/startstop*"));
}

ASP.Net MVC bundle has default ignore list and one of ignore list is ‘*.min.js’ files. Yes, any minified JavaScript file.

You can add the following code RegisterBundles to clear the ignore list before adding anything to the bundle.

bundles.IgnoreList.Clear();

Once you clear the list, you are also able to build your own ignore list.

bundles.IgnoreList.Ignore("");
 
Leave a comment

Posted by on June 12, 2015 in General

 

Tags: , ,

Software Laws

I was looking for a specific theorem called CAP theorem, but came across these interesting, sort of funny but somewhat true, software laws.

I think these laws are useful to get better understanding of philosophy behind a software or computer science in general.

  • Atwood’s Law

    Any software that can be written in JavaScript will eventually be written in JavaScript.

  • Brooks’s Law

    Adding manpower to a late software project makes it later.

  • Conway’s law

    Any piece of software reflects the organizational structure that produced it.

  • Miller’s law

    To understand what another person is saying, you must assume that it is true and try to imagine what it could be true of.

  • Wirth’s law

    Software gets slower faster than hardware gets faster.

 
Leave a comment

Posted by on March 1, 2015 in General

 

Tags: , , , ,

Determine Hierarchy Name Based on Inconsistent Level

Below are sets of inconsistent arrays that represents level in hierarchy:

  • [0, 1, 2]
  • [0, 1]
  • [0]

The order of hierarchy is (from the top to the bottom):

  • Director
  • Manager
  • Employee

The highest number in the array represents the bottom level in the hierarchy. The lowest number in the array represents higher level in the hierarchy.

So, given [0, 1, 2]: 0 means Director, 1 means Manager and 2 means Employee. And given [0, 1]: 0 means Manager and 1 means Employee.

What’s the most efficient way to assign LevelName property in the following data set. The answer doesn’t have to use specific programming language.

[{
    Fullname: "Bob",
    ReportTo: "",
    Level: "0",
    LevelName: ""
},{
    Fullname: "John",
    ReportTo: "Bob",
    Level: "1",
    LevelName: ""
},{
    Fullname: "Sally",
    ReportTo: "John",
    Level: "2",
    LevelName: ""
},{
    Fullname: "David",
    ReportTo: "John",
    Level: "2",
    LevelName: ""
},{
    Fullname: "Rachel",
    ReportTo: "Bob",
    Level: "1",
    LevelName: ""
},{
    Fullname: "Peter",
    ReportTo: "Rachel",
    Level: "2",
    LevelName: ""
}]
 
Leave a comment

Posted by on January 28, 2015 in General

 

Tags: , , ,

More Comprehensive Naming Convention

Indentation

Indentation

Indentation must be used if the line is associated with the previous line. When indentation is needed, use conventional indentation (one “Tab”).

Example 1:

<div id="content">
    <table>
        <tr>
            <td class="control_title">
            </td>
        </tr>
    </table>
</div>

Example 2:

public string indentation
{
    get
    {
        return _indentation;
    }
    set
    {
        _indentation = value;
    }
}

Wrapping Lines

Avoid lines longer than 120 characters. When an expression will not fit on a single line, break it with conventional indentation in new line.

Example:

string _xmlData = "<?xml version=\"1.0\"?>" + "\r\n" +
    "<!DOCTYPE ddtp=\"http://dtd.wctp.org/wctp-dtd-v1r1.dtd\">" + "\r\n" +
    "<wctp-Operation wctpVersion=\"wctp-dtd-v1r1\">" + "\r\n" +
    "<wctp-SubmitRequest>" + "\r\n" +
    "<wctp-SubmitHeader submitTimestamp=\"" + _timestamp + "\">" + "\r\n" +
    "<wctp-Originator senderID=\"application@chron.com\"/>" + "\r\n" +
    "<wctp-MessageControl messageID=\"001\"/>" + "\r\n" +
    "<wctp-Recipient recipientID=\"" + recipient + "@arch.com\"/>" + "\r\n";

 

Naming Convention (Server Code)

Identifier Naming Convention

Identifier Case Examples Rules
Comment Clear, short and descriptive.
Class PascalCase Person
BankVault
ImageSprite
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
Method(Private) PascalCase with “_” prefix _UpdateScore(…)
_UpdateUrl(…)
_UpdateID(…)
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Verbs.
Method(Public) PascalCase UpdateScore(…)
UpdateUrl(…)
UpdateID(…)
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Verbs.
Method for Ajax (Private and public) PascalCase following text “Ajax” SavePeopleAjax
GetPropertyAjax
_DeleteGroupAjax
Method for ajax is a method that only called with ajax.
For private, prefix with “_”.
Common Method (Private and public) PascalCase following text “Common” GetStateCommon
_GetAnswerCommon
_SaveStateCommon
Common method is a method that could be use in different controllers/pages.
For private, prefix with “_”.
Namespace PascalCase Chronicle.IT.BasicFunctions
Chronicle.IT.Ftp
Chronicle.IT.Xml
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Use $lt;company_name$gt; as root.
Interface PascalCase with “I” prefix IDisposable
IWidgetXml
IUserID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Parameter camelCase recordID
personName
previousUrl
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.
Property / Variable (Private) camelCase with “_” prefix _backColor
_internalXml
_userID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Property / Variable (Public) PascalCase BackColor
InternalXml
UserID
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.

Object Type Naming Convention

Additional object’s type can be added to precede some identifiers in order to distinguish the object type. If the object’s type is added, abbreviate the object type according to the following rules:

Object Type Abbreviated Object Type Examples
Array arr _arrBackColors
_arrInternalXml
arrUserID
String str _strBackColor
_strInternalXml
strUserID

 

Naming Convention (Client Code)

CSS & HTML

Identifier Case Examples Rules
Class dash-separated sort-column
portlet-header
portlet-content
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
All lowercase.
HTML Element camelCase ddlPropertyType
txtName
Start with 3 letters of specified element.
HTML Element (For) PascalCase Group
Property
People.FirstName
For is html element generated by mvc html helper that bound to the specific property.

JavaScript

Identifier Case Examples Rules
Comment Clear, short and descriptive.
Parameter camelCase dashboardResult
peopleResult
currentUrl
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores.
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.
Property / Variable (Private) camelCase with “_” prefix _savePreference
_currentUrl
_parent
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.
Property / Variable (Public) PascalCase SavePreference
CurrentUrl
Parent
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
No underscores (except the prefix).
Optional object type can be added. See “Object Type Naming Convention” section.
Nouns.

Json

Identifier Case Examples Rules
Name PascalCase Person
Status
Parent
Children
Acronyms of 3 or more letters should use pascal case instead of all caps.
Avoid abbreviations (unless it is widely used, like URL, HTML).
Keep names simple and descriptive.
No underscores.
Nouns.
Avoid using two words or more.
 
Leave a comment

Posted by on October 9, 2014 in General

 

Tags: , , , ,

 
%d bloggers like this: