Bubble Sort
The bubble sort makes multiple passes through a list. It compares adjacent items and exchanges those that are out of order. Each pass through the list places the next largest value in its proper place. In essence, each item “bubbles” up to the location where it belongs.
If there are n items in the list, then there are n−1 pairs of items that need to be compared on the first pass. It is important to note that once the largest value in the list is part of a pair, it will continually be moved along until the pass is complete.
At the start of the second pass, the largest value is now in place. There are n−1 items left to sort, meaning that there will be n−2 pairs. Since each pass places the next largest value in place, the total number of passes necessary will be n−1. After completing the n−1 passes, the smallest item must be in the correct position with no further processing required.
function countSwaps(a) {
let numSwaps = 0;
for (let p = a.length ; p > 0 ; p--) {
for (let x = 0; x < p - 1 ; x++) {
if (a[x] > a[x + 1]) {
let swap = a[x];
a[x] = a[x + 1];
a[x + 1] = swap;
numSwaps++;
}
}
}
console.log(`Array is sorted in ${numSwaps} swaps.`);
console.log(`First Element: ${a[0]}`);
console.log(`Last Element: ${a[a.length -1]}`);
}
References:
- https://runestone.academy/runestone/books/published/pythonds/SortSearch/TheBubbleSort.html
What is Immediately-Invoked Function Expression (IIFE) ?
An IIFE or Immediately Invoked Function Expression is a function that is gonna get invoked or executed after its creation or declaration. The syntax for creating IIFE is that we wrap the function (){} inside a parentheses () or the Grouping Operator to treat the function as an expression and after that we invoke it with another parentheses (). So an IIFE looks like this
(function(){})().
An Immediately-Invoked Function Expression can be used to “lock in” values and effectively save state.
// This doesn't work like you might think, because the value of `i` never
// gets locked in. Instead, every link, when clicked (well after the loop
// has finished executing), alerts the total number of elements, because
// that's what the value of `i` actually is at that point.
var elems = document.getElementsByTagName( 'a' );
for ( var i = 0; i < elems.length; i++ ) {
elems[ i ].addEventListener( 'click', function(e){
e.preventDefault();
alert( 'I am link #' + i );
}, 'false' );
}
// This works, because inside the IIFE, the value of `i` is locked in as
// `lockedInIndex`. After the loop has finished executing, even though the
// value of `i` is the total number of elements, inside the IIFE the value
// of `lockedInIndex` is whatever the value passed into it (`i`) was when
// the function expression was invoked, so when a link is clicked, the
// correct value is alerted.
var elems = document.getElementsByTagName( 'a' );
for ( var i = 0; i < elems.length; i++ ) {
(function( lockedInIndex ){
elems[ i ].addEventListener( 'click', function(e){
e.preventDefault();
alert( 'I am link #' + lockedInIndex );
}, 'false' );
})( i );
}
References:
- http://benalman.com/news/2010/11/immediately-invoked-function-expression/
- https://dev.to/macmacky/70-javascript-interview-questions-5gfi#26-what-is-an-iife-what-is-the-use-of-it
Hoisting in JavaScript
Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution.
Variable hoisting
console.log(hoist); // Output: undefined
var hoist = 'The variable has been hoisted.';
function hoist() {
console.log(message); // Output: undefined
var message='Hoisting is all the rage!'
}
hoist();
function hoist() {
a = 20;
var b = 100;
}
hoist();
console.log(a);
/*
Accessible as a global variable outside hoist() function
Output: 20
*/
console.log(b);
/*
Since it was declared, it is confined to the hoist() function scope.
We can't print it out outside the confines of the hoist() function.
Output: ReferenceError: b is not defined
*/
This means that, all undeclared variables are global variables.
In EcmaScript2015(ES6), let
and const
are hoisted but not initialized.
console.log(x); // Cannot access 'x' before initialization
let x = 10;
Function hoisting
hoisted(); // Output: "This function has been hoisted."
function hoisted() {
console.log('This function has been hoisted.');
};
Function expressions, however are not hoisted.
expression(); //Output: "TypeError: expression is not a function
var expression = function() {
console.log('Will this work?');
};
var text = 'outside';
function print(){
console.log(text);
var text = 'inside';
};
print(); // Output: undefined, as only declaration was hoisted, no initialization happened.
References:
What is Promise Chaining?
A common need is to execute two or more asynchronous operations back to back, where each subsequent operation starts when the previous operation succeeds, with the result from the previous step. We accomplish this by creating a promise chain.
In the old days, doing several asynchronous operations in a row would lead to the classic callback pyramid of doom:
doSomething(function(result) {
doSomethingElse(result, function(newResult) {
doThirdThing(newResult, function(finalResult) {
console.log('Got the final result: ' + finalResult);
}, failureCallback);
}, failureCallback);
}, failureCallback);
With modern functions, we attach our callbacks to the returned promises instead, forming a promise chain:
doSomething()
.then(function(result) {
return doSomethingElse(result);
})
.then(function(newResult) {
return doThirdThing(newResult);
})
.then(function(finalResult) {
console.log('Got the final result: ' + finalResult);
})
.catch(failureCallback);
Reference:
What is AMD, CommonJS
AMD (Asynchronous Module Definition) The AMD module format itself is a proposal for defining modules where both the module and dependencies can be asynchronously loaded.
“define” method for facilitating module definition and a “require” method for handling dependency loading.
define('myModule',
['foo', 'bar'],
// module definition function
// dependencies (foo and bar) are mapped to function parameters
function ( foo, bar ) {
// return a value that defines the module export
// (i.e the functionality we want to expose for consumption)
// create your module here
var myModule = {
doStuff:function(){
console.log('Yay! Stuff');
}
}
return myModule;
});
require(['foo', 'bar'], function ( foo, bar ) {
// rest of your code here
foo.doSomething();
});
CommonJS (CJS)
CJS module is a reusable piece of JavaScript which exports specific objects made available to any dependent code - there are typically no function wrappers around such modules.
// package/lib is a dependency we require
var lib = require('package/lib');
// some behaviour for our module
function foo(){
lib.log('hello world!');
}
// export (expose) foo to other modules
exports.foo = foo;
// an application consuming 'foobar'
// access the module relative to the path
// where both usage and module files exist
// in the same directory
var foobar = require('./foobar').foobar,
test = new foobar();
test.bar(); // 'Hello bar'
References
- https://addyosmani.com/writing-modular-js/
- https://requirejs.org/docs/whyamd.html#purposes