Confusing?  CommonJS, AMD, RequireJS, UMD, Modules in ES Harmony

A much more comprehensive documentation is written by Addy Osmani:

Writing Modular JavaScript With AMD, CommonJS & ES Harmony

All of these terms are related to manage growing complicated JavaScript source code in both client and server sides for better software engineering purpose.

A. How JavaScript is loaded into browser?

Normally:

  1. By the <script src="”source.js”" async="" defer="defer">
    tag. You can defer it, or make it asynchronous use the new attributes, although buggy.
  2. Use document.write:
    var tag = <script src="”source.js”" ></script >
    document.write(tag);
  3. Use appendchild(script):
    var script = document.createElement(‘script’);
    script.src = “http://googleapis.com”;
    document.documentElement.firstChild.appendChild(script);
  4. XHR and eval:
    $.ajax({url: url}).done(function(js){eval(js);})
  5. In Chrome, use <link rel=”prefetch” > to load resources
  6. Script loaders: CommonJS, AMD, RequireJS, curl.js, UMD, etc..

B. So, How, When And Why Script Loaders Are Appropriate

http://www.html5rocks.com/en/tutorials/speed/script-loading/

Most times, just use the traditional method to minify and concatenate all JavaScript files into a single file and put it just before </body> tag.

C. CommonJS

CommonJS defines a module format such that it works on both client and server side. The drawback for CommonJS in web browser is that it won’t simply allow asynchronous loading.

D. AMD

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module and its dependencies can be asynchronously loaded.

The signature function: define(id?, [dependencies?], factory)

E. RequireJS

It implements AMD and caters for simplified CommonJS wrapping.

F. UMD

The UMD pattern typically attempts to offer compatibility with the most popular script loaders of the day (e.g RequireJS amongst others). In many cases it uses AMD as a base, with special-casing added to handle CommonJS compatibility.

G. Modules in ES5

An ES6 module is a file containing JS code. There’s no special module keyword; a module mostly reads just like a script. There are two differences.

  • ES6 modules are automatically strict-mode code, even if you don’t write “use strict”;in them.
  • You can useimport and export in modules.

You differentiate the normal script and module by giving type attribute in the script tag,

i.e.: set script tag with type=”module”

https://hacks.mozilla.org/2015/08/es6-in-depth-modules/

https://www.nczonline.net/blog/2016/04/es6-module-loading-more-complicated-than-you-think/

Advertisements

NUS MComp CS5344 Big Data Technologies

Big Data. It is not important, you are not required to web-scrap some big size of data.

Technologies.Yes, this is the point.

You can learn mapReduce/Hadoop, recommendation systems, page ranks and all kinds of algorithms. They are really hard to understand and even harder to implement. So you are required to understand them to conquer the tests (people did get 0000 mark).

Three programming labs + 3 online-tests + 2 open-book algo tests + 1 final team project. There are a lot of things to learn if you want and the Professor is great.

Prepare: read all those algorithms in bid data areas.

Not relevant.

NUS MComp CS5224 Cloud Computing

Oh, Cloud computing sounds good.

The lectures are all about the basic concepts in cloud computing. You won’t learn any cloud technologies in the implementation level.

Learn IBM Bluemix, anyone uses or knows it? and Amazon cloud services in basics.

No programming needed. Two closed-book tests, middle term and the final.

Plus a 30% of team project using Cloud/Web/Viz skills. The project can be a simple one, but if you want grade A, then it must be creative and not simple.

You must memorize the lecture notes for the tests or you won’t get a high score.

NUS MComp IS5126 Hands On with Business Analytics

It’s good to take this course if you want to challenge yourself with learning introduction of Python programming and statistics. But, be sure to have programming background or a team member who is strong and willing to solve the assignments.

Two contiguous assignments about analysing the salaries of  NBA players. One big term project (50%) of any topic (better in casual analysis, which is hard). Plus a simple case study presentation.

Lectures are in MBA style case discussions, and not really useful if you are just a new graduate. OK. it’s hard to understand the materials which meant for MBA executives in Harvard. WTF!!!

No exams. The AP won’t fail anyone.

Prepare:

  1. statistics / business analysis background
  2. Python programming
  3. time-consuming (no kidding)

港股黑名单

炒股,如果你只是玩一点零花钱,比如2万块钱,你可以觉得赚亏一倍都没什么大不了,你下个月努力工作就赚回了。

如果你是用5年,10年的积蓄去买股票,那么,可得小心了。赚亏10%,就是你工作好几年赚来的血汗钱。

奇怪的是大多数人买个不到1万快钱的电脑都要货比三家,挑选品牌,但是买股票,却是几分钟内用屁股拍板。

股市的钱有那么好赚,华尔街就不需要存在了。

先贴一条新闻:香港老千股横行 李小加呼吁投资者小心别碰

然后贴一个黑名单

避免常见的几大庄家:

威利系、宏安系、中国星系、詹壳王系、庞壳王系、陈壳王系中的大部分、金利丰系中的大部分、萧才子系、抽水机官永义

然后再避免用大钱去赌创业股和股权集中度超过80%的公司。

我自己的黑名单总结。

JS Questions

1. Explain event delegation, what’s event bubbling/event propagation?

jQuery on DOM event delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

The basic idea behind this notation is DOM event bubbling. Say you have a structure like this:

<html>
<body>
<div id="container">
<ul id="list">
<li><span><a href="http://www.google.com">This is a link</a></span></li>
<li><span><a href="http://www2.google.com">This is a link</a></span></li>
<li><span><a href="http://www3.google.com">This is a link</a></span></li>

</ul>

</div>
</body>
</html>

when you click the text area ‘This is a link’, this ‘click’ event will bubble up to the DOM tree:

a -> span -> li -> ul -> div  -> body -> html -> document root.

So if you register a click event handler to the ul element, it will capture the ‘click’ event happened in a link.

// Attach a delegated event handler
$( "#list" ).on( "click"function( event ) {
var elem = $( this );
if ( elem.is( "[href^='http://www1']" ) ) {//match the element
elem.attr( "target", "_blank" );
}
});

Here you click ‘a’ event, the default action is to trigger some link to follow, to prevent this, use  event.preventDefault(). If you want to stop the bubbling process call event.stopPropagation().

2. Explain how prototypal inheritance works

Inheritance and the prototype chain

JavaScript only has one construct: objects. Each object has an internal link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. null, by definition, has no prototype, and acts as the final link in this prototype chain. Kinda of inheritance.

3. Explain why the following doesn’t work as an IIFE: function foo(){ }();. What needs to be changed to properly make it an IIFE? => (function foo(){})();

4. What’s the difference between a variable that is: null, undefined or undeclared?

Null is null value, undefined is for declared variable which has undefined value, undeclared means the variable is not declared before using it.

5. What is a closure, and how/why would you use one?

6. What’s a typical use case for anonymous functions? for loop. array.map

7. What’s the difference between host objects and native objects?

8. Difference between: function Person(){}, var person = Person(), and var person = new Person()?

The previous is to assign the function call result to person. Using new is to create an instance of the Person object.
9. What’s the difference between .call and .apply?

For .call you pass the parameters comma separated (like normal). For .apply you pass the parameters in an array.

10. Explain Function.prototype.bind.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

11. When would you use document.write()?

Seldom use.

12. What’s the difference between feature detection, feature inference, and using the UA string?

Browser object navigator.userAgent to detect the browser specific objects is feature detection. Feature inference is to use it as a method to guess some features in the browser.

13. Explain Ajax in as much detail as possible.

XMLHTTPREUEST.

14. What are the advantages and disadvantages of using Ajax?

Not updating the whole page.

15. Explain how JSONP works (and how it’s not really Ajax).

Return JSON data as callback in a Script manner to bypass same-origin policy.

16. Have you ever used JavaScript templating?
If so, what libraries have you used?
Handlerbar.

17. Explain “hoisting”.

E.g. call(); function call() { console.log(‘I am declared after the call, but it is ok.’)}

18. What’s the difference between an “attribute” and a “property”?
HTML tag attributes. and JS object property.

19. Why is extending built-in JavaScript objects not a good idea?

May lead bugs if someone else is to use the default function.

20. Difference between document load event and document DOMContentLoaded event?

Load event is fired after all page resources are loaded, DOMContentLoaded event is fired as soon as DOM tree is finished loading.

21. What is the difference between == and ===?

== for equality of values, and === for equality of values and types.

22. Explain the same-origin policy with regards to JavaScript.
JS can only work variables within the same global window environment from the same origin domain.

23. Make this work:
duplicate([1,2,3,4,5]); // [1,2,3,4,5,1,2,3,4,5]

duplicate(arr){ return arr.concat(arr);}

24. Why is it called a Ternary expression, what does the word “Ternary” indicate?

a ? b : c. Ternary means three parameters are present in this operand expression.

25. What is “use strict”;? what are the advantages and disadvantages to using it?

More stricter syntax check to expose bugs earlier.

26. Create a for loop that iterates up to 100 while outputting “fizz” at multiples of 3, “buzz” at multiples of 5 and “fizzbuzz” at multiples of 3 and 5

for i: 100: if (i%3 == 0) fizz;  if (i%5 == 0) buzz; if (i%15 == 0) fizzbuzz ;

27. Why is it, in general, a good idea to leave the global scope of a website as-is and never touch it?

Preserve the global value as it is, and you never know how others will use it. Save for reducing bugs.

28. Why would you use something like the load event? Does this event have disadvantages? Do you know any alternatives, and why would you use those?

Page load event can be used to detect all resources are loaded. Maybe use it to process DOM nodes or to trick CSS.

29. Explain what a single page app is and how to make one SEO-friendly.

SPA. Use semantics HTML.

30. What is the extent of your experience with Promises and/or their polyfills?
What are the pros and cons of using Promises instead of callbacks?

There are some cross-browsers support issues. Promise can handle asynchronous code more easily or construct good code blocks. more readable.

31. What are some of the advantages/disadvantages of writing JavaScript code in a language that compiles to JavaScript?

No trial before. Possible Compilation and debug may be hard with a nice or strict syntax.

32. What tools and techniques do you use debugging JavaScript code?

Chrome Dev Tools.

33. What language constructions do you use for iterating over object properties and array items?

for in loop for object properties and for of loop for array items. Or array.forEach for array items.

34. What do you think of AMD vs CommonJS?

35. Explain the difference between mutable and immutable objects.
What is an example of an immutable object in JavaScript?
What are the pros and cons of immutability?
How can you achieve immutability in your own code?

Mutable object can be changed after its creation, which immutable object doesn’t allow the change of itself. In JS, like strings and numbers are immutable. Say a = {x:2, y:203}, you can mutate it like this a.x = 20; If writing a large web app, there is loss of control on data objects in JS, and hence may cause many data inconsistencies or bugs when displaying data in JS.

Build immutable objects need not to change the original objects. Each change will create a new object and preserve the previous object.

Use Object.assign({target}, source) to perform mutation of objects.

35. Explain the difference between synchronous and asynchronous functions.

Synchronous function needs to wait for its execution completion and return the results back. It stops the other code running in a single-thread environment. While asynchronous function fires the execution and continues to run the other code. It returns the result to interrupt the current code execution once completed.

36. What is the difference between call stack and task queue?

Call stack is a data structure to store method calls within a programme, while task queue is to use to store the sequential tasks to run. Each task could be a small programme.

A Short Course: Compilers, Assemblers, Linkers, Loaders

Source and copy right @ https://courses.cs.washington.edu/courses/cse378/97au/help/compilation.html

Assembler: A computer will not understand any program written in a language, other than its machine language. The programs written in other languages must be translated into the machine language. Such translation is performed with the help of software. A program which translates an assembly language program into a machine language program is called an assembler. If an assembler which runs on a computer and produces the machine codes for the same computer then it is called self assembler or resident assembler. If an assembler that runs on a computer and produces the machine codes for other computer then it is called Cross Assembler.

Assemblers are further divided into two types: One Pass Assembler and Two Pass Assembler. One pass assembler is the assembler which assigns the memory addresses to the variables and translates the source code into machine code in the first pass simultaneously. A Two Pass Assembler is the assembler which reads the source code twice. In the first pass, it reads all the variables and assigns them memory addresses. In the second pass, it reads the source code and translates the code into object code.

Compiler: It is a program which translates a high level language program into a machine language program. A compiler is more intelligent than an assembler. It checks all kinds of limits, ranges, errors etc. But its program run time is more and occupies a larger part of the memory. It has slow speed. Because a compiler goes through the entire program and then translates the entire program into machine codes. If a compiler runs on a computer and produces the machine codes for the same computer then it is known as a self compiler or resident compiler. On the other hand, if a compiler runs on a computer and produces the machine codes for other computer then it is known as a cross compiler.

Interpreter: An interpreter is a program which translates statements of a program into machine code. It translates only one statement of the program at a time. It reads only one statement of program, translates it and executes it. Then it reads the next statement of the program again translates it and executes it. In this way it proceeds further till all the statements are translated and executed. On the other hand, a compiler goes through the entire program and then translates the entire program into machine codes. A compiler is 5 to 25 times faster than an interpreter.

By the compiler, the machine codes are saved permanently for future reference. On the other hand, the machine codes produced by interpreter are not saved. An interpreter is a small program as compared to compiler. It occupies less memory space, so it can be used in a smaller system which has limited memory space.

Linker: In high level languages, some built in header files or libraries are stored. These libraries are predefined and these contain basic functions which are essential for executing the program. These functions are linked to the libraries by a program called Linker. If linker does not find a library of a function then it informs to compiler and then compiler generates an error. The compiler automatically invokes the linker as the last step in compiling a program.

Not built in libraries, it also links the user defined functions to the user defined libraries. Usually a longer program is divided into smaller subprograms called modules. And these modules must be combined to execute the program. The process of combining the modules is done by the linker.

Loader: Loader is a program that loads machine codes of a program into the system memory. In Computing, a loader is the part of an Operating System that is responsible for loading programs. It is one of the essential stages in the process of starting a program. Because it places programs into memory and prepares them for execution. Loading a program involves reading the contents of executable file into memory.  Once loading is complete, the operating system starts the program by passing control to the loaded program code. All operating systems that support program loading have loaders. In many operating systems the loader is permanently resident in memory.

Compilers, Assemblers, Linkers, Loaders: A Short Course

This document briefly describes what happens when you compiler and run
a program. More details can be found in Compilers, Principles,
Techniques, and Tools
by Aho, Sethi, and Ullman (CSE 401 book)
and Appendix A of Computer Organization and Design by
Patterson and Hennesey (CSE 378 book).

Compiling a Program

When you type cc at the command line a lot of stuff happens.
There are four entities involved in the compilation process:
preprocessor, compiler, assembler, linker (see Figure 1).

 

The internals of cc

Figure 1: The internals of cc.

 

First, the C preprocessor cpp expands all those macros
definitions and include statements (and anything else that starts with
a #) and passes the result to the actual compiler. The
preprocessor is not so interesting because it just replaces some short
cuts you used in your code with more code. The output of cpp
is just C code; if you didn’t have any preprocessor statements in your
file, you wouldn’t need to run cpp. The preprocessor does
not require any knowledge about the target architecture. If you had
the correct include files, you could preprocess your C files on a
LINUX machine and take the output to the instructional machines and
pass that to cc. To see the output of a preprocessed file,
use cc -E.

The compiler effectively translates preprocessed C code into assembly
code, performing various optimizations along the way as well as
register allocation. Since a compiler generates assembly code
specific to a particular architecture, you cannot use the assembly
output of cc from an Intel Pentium machine on one of the
instructional machines (Digital Alpha machines). Compilers are very
interesting which is one of the reasons why the department offers an
entire course on compilers (CSE 401). To see the assembly code
produced by the compiler, use cc -S.

The assembly code generated by the compilation step is then passed to
the assembler which translates it into machine code; the resulting
file is called an object file. On the instructional machines, both
cc and gcc use the native assembler as that
is provided by UNIX. You could write an assembly language program and
pass it directly to as and even to cc (this is what
we do in project 2 with sys.s). An object file is a binary
representation of your program. The assembler gives a memory
location
to each variable and instruction; we will see later that
these memory locations are actually represented symbolically or via
offsets. It also make a lists of all the unresolved references that
presumably will be defined in other object file or libraries,
e.g. printf. A typical object file contains the
program text (instructions) and data (constants and strings),
information about instructions and data that depend on absolute
addresses, a symbol table of unresolved references, and possibly some
debugging information. The UNIX command nm allows you to
look at the symbols (both defined and unresolved) in an object file.

Since an object file will be linked with other object files and
libraries to produce a program, the assembler cannot assign absolute
memory locations to all the instructions and data in a file. Rather,
it writes some notes in the object file about how it assumed
things were layed out. It is the job of the linker to use these notes
to assign absolute memory locations to everything and resolve any
unresolved references. Again, both cc and gcc on
the instructional machines use the native linker, ld. Some
compilers chose to have their own linkers, so that optimizations can
be performed at link time; one such optimization is that of aligning
procedures on page boundaries. The linker produces a binary
executable that can be run from the command interface.

Notice that you could invoke each of the above steps by hand. Since
it is an annoyance to call each part separately as well as pass the
correct flags and files, cc does this for you. For example,
you could run the entire process by hand by invoking /lib/cpp
and then cc -S and then /bin/as and finally
ld. If you think this is easy, try compiling a simple
program in this way.

Running a Program

When you type a.out at the command line, a whole bunch of
things must happen before your program is actually run. The loader
magically does these things for you. On UNIX systems, the loader
creates a process. This involves reading the file and creating an
address space for the process. Page table entries for the
instructions, data and program stack are created and the register set
is initialized. Then the loader executes a jump instruction to the
first instruction in the program. This generally causes a page fault
and the first page of your instructions is brought into memory. On
some systems the loader is a little more interesting. For example, on
systems like Windows NT that provide support for dynamically loaded
libraries (DLLs), the loader must resolve references to such libraries
similar to the way a linker does.

Memory

Figure 2 illustrates a typical layout for program memory. It is the
job of the loader to map the program, static data (including globals
and strings) and the stack to physical addresses. Notice that the
stack is mapped to the high addresses and grows down and the program
and data are mapped to the low addresses. The area labeled
heap is where the data you allocate via malloc is
placed. A call to malloc may use the sbrk system
call to add more physical pages to the program’s address space (for
more information on malloc, free and sbrk,
see the man pages).

 

Memory layout

Figure 2: Memory layout.

 

Procedure Call Conventions

A call to a procedure is a context switch in your program. Just like
any other context switch, some state must be saved by the calling
procedure, or caller, so that when the called procedure, or
callee, returns the caller may continue execution without
distraction. To enable separate compilation, a compiler must follow a
set of rules for use of the registers when calling procedures. This
procedure call convention may be different across compilers
(does cc and gcc use the same calling convention?)
which is why object files created by one compiler cannot always be
linked with that of another compiler.

A typical calling convention involves action on the part of the caller
and the callee. The caller places the arguments to the callee in some
agreed upon place; this place is usually a few registers and the
extras are passed on the stack (the stack pointer may need to be
updated). Then the caller saves the value of any registers it will
need after the call and jumps to the callee’s first instruction. The
callee then allocates memory for its stack frame and saves any
registers who’s values are guaranteed to be unaltered through a
procedure call, e.g. return address. When the callee is
ready to return, it places the return value, if any, in a special
register and restores the callee-saved registers. It then pops the
stack frame and jumps to the return address.


Original version from CSE451, Autumn 1996.
Modified by wolman@cs.washington.edu, Autumn 1997.