JavaScript Notebook. Saw, Shura, saw!*

Javascript / UI / Web technologies notes / * – "Saw Shura, Saw! These are golden kettlebells…" (from "The Little Golden Calf" by Ilf and Petrov)

Tackling Functional JS

Lets say we have an api route defined with parameters and we have replacements for them. Using functional approach lets write some code to get the updated url.

GIVEN url = "/albums/:id/title/:action"
OR    url = "/albums/{id}/title/{action}"

WHEN  replacements = {id: 5, action: 'update'}

THEN  output "/albums/5/title/update"

Just for fun lets do this with imperative approach for the 1st example of the url (with ‘:param’).

var url = "/albums/:id/title/:action",
    params = url.match(/:[a-z]+/g),
    replacements = {id: 5, action: 'update'};
params && params.forEach(function (p) {
    url = url.replace(p, replacements[p.slice(1, p.length)]);
});
console.log(url);
// >>> /albums/5/title/update 

Now lets do the same in a functional style. We will use ramda.js as a functional library.

At first, lets write some helpers:

var getParams = _.curry(function (pattern, str) {
  return str.match(pattern);
});
var getParamsColumned = getParams(/:[a-z]+/g);
var getParamsBracketed = getParams(/{[a-z]+}/g);
var getParamName = function (param) {
  return param.match(/[a-z]+/g);
};
var replaceNeedle = _.curry(function (getParamName, params, url, needle) {
  return url.replace(needle, params[getParamName(needle)]);
})(getParamName);

Now lets define the actual action and execute:

var urlReplaceParams = function (url, needles, params) {
  return needles.reduce(replaceNeedle(params), url);
};
console.log(
  urlReplaceParams(url, getParamsColumned(url), replacements)
);
// >>> "/albums/5/title/update"

// OR
url = "/albums/{id}/title/{action}";
console.log(
  urlReplaceParams(url, getParamsBracketed(url), replacements)
);
// >>> "/albums/5/title/update"

Slightly different variant:

var urlReplaceParams = function (url, replacements) {
  return _.reduce(
    replaceNeedle(replacements),
    url,
    getParamsColumned(url)
  );
};
console.log(
  urlReplaceParams(url, replacements)
);
// >>> "/albums/5/title/update"

Unfortunately, in this example the functional way is much more difficult to both implement and read…

JSbin where I played with the code is here.

Advertisements

(draft) JavaScript: essentials

Lexical scope

Lexical scope of a function is statically defined by the function’s physical placement within the written source code. The outer lexical scope of any given function is defined by its ancestors in the lexical hierarchy.

Closure

Accessing variables outside of the immediate lexical scope creates a closure.

VariableEnvironment

The global object has an associated execution context. Additionally every invocation of a function establishes and enters a new execution context. The execution context is the dynamic counterpart to the static lexical scope. Each execution context defines a VariableEnvironment which is a repository for variables declared by that context. (ES5 10.4, 10.5)

When a given execution context encounters a function definition in the code, a new function object is created with an internal property named [[scope]] (as in lexical scope) which references the current VariableEnvironment. (ES5 13.0-2)

(draft) Functional JS

This is a post in progress.

# Some terminology and definitions

## Monoid and Semigroup

### Examples first:
– The integers under addition is a monoid.
– The positive numbers under addition is a semigroup (no identity element).

### Definitions:

Monoid is a system (a type plus an operation) that obeys the following three rules [1]:
– Rule 1 (Closure): The result of combining two things is always another one of the things: 1 + 2 = 3
– Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn’t matter: 1 + (2 + 3) = (1 + 2) + 3
– Rule 3 (Identity element): There is a special thing called “zero” such that when you combine any thing with “zero” you get the original thing back: 1 + 0 = 1

Semigroup is a system that obeys the first two rules but lacks an identity element.

#Maybe monad

var log = function (x) { console.log(x); };
_.map(log, [1,2,3])
>>> 1
>>> 2
>>> 3
>>> [1, 2, 3]

_.map(log, null)
>>> TypeError: Cannot read property 'length' of null

_.maybe(_.map)(log, [1,2,3])
>>> 1
>>> 2
>>> 3
>>> [1, 2, 3]

_.maybe(_.map)(log, null)
>>> undefined

In the example above I used version 0.2 of ramda.js. In other libraries maybe monad wraps a value so that you can compose it with other functions. But in ramda  it wraps a function that you want to behave correctly if there is a null argument instead of expected.

UPDATE: This was true for version 0.2 of ramda but then the “maybe” method was removed and is no longer a part of the library.

# Links
http://fsharpforfunandprofit.com/posts/monoids-without-tears/
http://buzzdecafe.github.io/code/2014/05/16/introducing-ramda/
http://osteele.com/sources/javascript/functional/

(draft) Bitwise operators and numbers in JS

I am just trying to figure out for myself the bitwise operators in JavaScript. This includes understanding of how data is represented in memory (my guess is this is more for numbers than for other type of data).

There are the following bitwise operators available (MDN: Bitwise operators):

&, |, ^, ~, <<, >>, >>>

To convert a decimal number into a binary representation:

> (7).toString(2);
  "111"

Lets look at a float number now:

> (7.5).toString(2);
  "111.1"

> (7.6).toString(2)
  "111.1001100110011001100110011001100110011001100110011"
Mantissa is:
   1.1110011001100110011001100110011001100110011001100110
Exponent is:
   10000000001 (+2)

> (70.6).toString(2)
  "1000110.100110011001100110011001100110011001100110011"
> (7000000.6).toString(2)
  "11010101100111111000000.10011001100110011001100110011"

What are the maximum number/integer and why

The Number object contains interesting properties:

> Number.MAX_VALUE
  1.7976931348623157e+308
> Number.MAX_SAFE_INTEGER
  9007199254740991

The max safe integer according to ECMA6 draft is 253−1. Where does this come from?

Representation in memory

Lets look at how numbers are represented in memory (2ality: How numbers are encoded in JavaScript):

“Numbers are stored in a binary format, in 64 bits. These bits are allotted as follows: The fraction occupies bits 0 to 51, the exponent occupies bits 52 to 62, the sign occupies bit 63.”

sign     exponent      fraction
(1 bit)  (11 bit)      (52 bit)
63       62   -   52   51   -   0

Now its clear why the max safe integer is 253−1: its simply because we have 52 bits for it:

> Math.pow(2,53)-1
  9007199254740991

OK, but where does the max number of 1.7976931348623157e+308 come from?

We have 11 bits for the exponent part, both positive and negative:

> Math.pow(2,11) - 1   |   > (2047).toString(2)   |   > (2047).toString(2).length + ' bits'
  2047                 |     "11111111111"        |     11 bits

1023 is the Bios, meaning that the exponent of zero is stored in exponent field as 1023.

Here is an interesting tool to inspect the memory representation of a number: IEEE-754 Analysis and the actual standard: IEEE Standard 754 Floating Point Numbers

(draft) AngularJS – bird’s-eye view

1. Key points
2. Relation to MVC
3. Structure (SOA)
4. File organization

Key points of AngularJS

  • DI (Dependency Injection)
  • Directives
  • Testing oriented

Dependency Injection in brief means that in our code we don’t refer to any globally available objects. Every external dependency is injected into current scope by framework’s injector. This encourages us to write modular and thus testable code with a good separation of concerns.

Angular Directive in brief is a reusable component that consists of a view and a controller, allows to augment variables and data (html/template as a content), and extends html vocabulary with new HTML tags or attributes. This idea is known in HTML5 as Web Components.

The creator of AngularJS said that the framework was designed with testing in mind. The credit of testing with ease goes to both: framework designers (who chose DI pattern which allows us to mock everything we use inside our code) and google test engineers (who built Karma and Protractor which are great tools for unit and end-to-end testing).

Relation to MVC

In the Throne of JS, conference that happened in Toronto in 2012, AngularJS team stated that their framework is MV* (star). Usually the last component of the pattern stands either for Controller or View Model or Presenter or Adapter. AngularJS does have Controllers but they are different from MVC controllers, they are more like view models or presentational models.

Always coupled with a view Angular’s controller stores:

  • view’s state (data bindings),
  • view related logic (or programming codesnips as helpers to be used inside view’s declarative logic),
  • and methods being used to handle user interactions (aka event handlers).

Also, there is no models as framework components (e.g. compared to BackboneJS models *LINK*). You have to use JavaScript native objects and arrays to store data in Angular Services. Of course you are free to use any external libraries for this, but you will found nothing out of the box.

In version 2 Angular team is planning to introduce data layer *LINK*. ECMAScript version 6  adds classes to language natives, and in Angular 2.0 we will see Model class (ES6 class) as an extensible abstraction layer on top of low-level storage and network utilities to manage fetching , caching, and querying data.

There are articles in the web *LINKS* stating that Angular is SOA  rather than MVC. Lets look at this.

Structure (SOA)

So, what are Angular’s Services and how to eat them?

Angular has a Provider component and three “sugars” to use it: Value, Factory, Service. The result of each is Angular’s “global” object that you can work with and inject into application components. Really they are either:

  • Simple values (constants, strings, numbers, booleans) – “Value”,
  • Objects with an optional predefined (during the configuration stage) scope – “Factory”,
  • or instances (as singletons) – “Service”.

From the application point of view Services are like “application brains” and store application logic and state. From here we Controllers could be seen as “View’s brains” storing a view specific state and logic.

Here is a diagram I just love (from here *LINK*):

ngbrains

 

(draft) AngularJS Architecture

First time I heard about AngularJS was from “Throne Of JS” conference in Toronto back in 2012. Angular team claimed their project MV* (star) framework. Since then AngularJS released their 1.0.0 version and became one of the most popular JavaScript frameworks. And now we are looking forward to version 2.0.

I am really interested in the architecture of AngularJS applications and in this post I am just trying to settle a view of the subject for myself.

The article about Angular architecture that inspired me to write this post: “Angular.js Large Scale Architecture and StarCraft“. I will be using this one as the first source for this post.

The most interesting implementation of Angular app I ever met was this one with RequireJS: “Thomas Burleson Angular and RequireJS“. I would like to create a yeoman generator for this pattern (yeoman).

Unique features: Directives and DI (Dependency Injection)

Key points: DI, Directives, Testing oriented.

Modularity: “features are in a take-it-or-leave-it single package”. You incur the download price for every piece whether you use it or not.

AngularJS Structure:

  • Services (application brain): Logic + State
  • Controllers (mini brains – less capable, and responsible of view specific tasks): Logic + State
  • Views (display, user interaction): Template + Directives + Filters

Controller:

  • is more like a View Model or Presentation Model.
  • holds “scope” object responsible for:
    • view data
    • presentation state
    • reaction behaviour
  • sets initial state values.
  • is a glue between view and services.
  • knows nothing about the view (Separation of Concerns) -> testing and reuse!
  • No imperative logic allowed.

“Angular.js isn’t really MVC. Its controllers are actually presentation models, its views are plain templates and it’s models… well.. there aren’t any, they are just plain old objects and arrays.”

“When you want to extend your application cross cutting capabilities, you add a service, a filter or a directive. And when you want to add another screen or page specific view, you can add a template/controller pair.”

Views:

  • (?) Declarative (present and react).

DI: Providers and Injectors

Plan:
– blog title idea
– article
– presentation
– generator
– echojs
– linkedin

(draft) Understanding “this” keyword in ES6 from JavaScript spec

ECMA-262 versions 5 and 6 are a bit different in defining “this” keyword. Lets see what will be changed with ES6 coming.

Quick dive into the 5th edition

 

For the 5th edition the best article I ever read was one by Angus Croll Understanding JavaScript’s this keyword. In the 2nd part of his article “What you might want to know” Angus explored the specification, and the resulting explanation is just brilliant. IMHO. Here is a brief and very simplified summary.

  1. 5th edition 11.1.1 The this Keyword: “The this keyword evaluates to the value of the ThisBinding of the current execution context“.
  2. ThisBinding is set to the object coercion of the abstract argument thisValue.
  3. thisValue comes from baseValue.
  4. And finally baseValue depends on the current execution context:
    1. baseValue is the identifier preceding the dot when function is expressed as a property.
    2. In a baseless function invocation thisValue results in a ThisBinding value of the global object (or undefined in strict mode).
    3. Invoking function as a constructor with new creates an object that gets assigned as the thisValue, so its the new instance.
    4. Invoking using Function.prototype.apply or .call will result in the 1st argument.

Some examples:

// as a method/property:
var foo = {
    bar: function() { return this ;}
}
foo.bar();         // -> foo

// baseless function:
var b = foo.bar;
b();               // -> window

// using constructor:
var user = new function () {
    this.getThis = function () { return this; }
}
user.getThis();    // -> user

For more examples you could look at Mozilla Developer Network resource: Web/JavaScript/Reference/Operators/this.

The easiest way to remember the most common cases is:

– If there is a “base” when you execute the function then “this” will result in the “base”.
– Without the “base” you will get the global object.

The most common use cases to get lost are:
– passing a function as an argument.
– using a function as an event handler.

The confusion comes when you do this and see the “base” before the method. But think this way – we are passing the reference, so when the function actually gets executed there will be no “base” any more. The words “execution context” should help to remember this.

var foo = {
    bar: function() { return this ;}
};
var z = function (f) {
    return f(); // here we don't have the "base"
};
z(foo.bar);     // -> window

Lets get our hands dirty in the 6th edition

 

6th edition 12.1.1 The this Keyword: “Return the result of calling the ResolveThisBinding abstract operation.”

Right away we can see they did something about it. Lets try to explore the full path.

12.1.1 The this Keyword
12.1.1.1 Runtime Semantics: Evaluation
PrimaryExpression : this
Return the result of calling the ResolveThisBinding abstract operation.

8.3.3 ResolveThisBinding
The abstract operation ResolveThisBinding determines the binding of the keyword this using the LexicalEnvironment of the running execution context. ResolveThisBinding performs the following steps:

Let env be the result of performing the GetThisEnvironment abstract operation.
Return the result of calling the GetThisBinding concrete method of env.

8.3.2 GetThisEnvironment
The abstract operation GetThisEnvironment finds the lexical environment that currently supplies the binding of the keyword this. GetThisEnvironment performs the following steps:

1. Let lex be the running execution context’s LexicalEnvironment.
2. Repeat
a. Let envRec be lex’s environment record.
b. Let exists be the result of calling the HasThisBinding concrete method of envRec.
c. If exists is true, then return envRec.
d. Let outer be the value of lex’s outer environment reference.
e. Let lex be outer.

NOTE The loop in step 2 will always terminate because the llst of environments always ends with the global environment which has a this binding.