Template for Divided Conquer Algorithm
2020-05-21Disclaimer
This article is originally based on my understanding of this concept. No guarantee on the accuracy.๐
Template:
1.base case
2.split to smaller sacle
(directly slice from the array otherwise maintain the index, and dynamically updated every call)
3.recursion
4.combination
(define the combination function and pass the returned value from recursion as parameter)
Letโs see the examples from easy to moderate
๐ Search the max&min value
1 | function searchMaxMin(arr) { |
๐๐ Merge Sorting
1 | const mergeSort=arr=>{ |
The call-stack would run in this sequence:
1 | merge(mergesort(3,1),mergersort(5,0,2)) |
๐๐ Quick Sorting
1 | function quick(nums) { |
๐๐ 169. Majority Element
Understanding Promise part 2
2020-05-16Disclaimer
This article is originally based on my understanding of this concept. No guarantee on the accuracy.๐
โThe Promise
object represents the eventual completion (or failure) of an asynchronous operation, and its resulting value.โ
It was introduced to handle asynchronous operation like synchronous opeartion and avoid the callback hell.
1 | doSomething(function(result) { |
Common asynchronous-operation
- setTimeOut, setInterval
- XHR request (fetch api)
- Event Listening
Thansk to promiseโs .then() chaining, we can put the callback outside๏ผ
1 | doSomething() |
*This all based on modern API that returning a promise. That is to say, the promise chains starts with an API function which returns a promise. *
We can create our own promise as well. Although itโs not typical practice but it can be helpful to โpromisifyโ some old callback-style API then chain the handler.
Letโs look at how a promise is created.
1 | var promise = new Promise( |
An example of wrapping a callback-style function with Promise:
1 | const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); |
Understanding Promise part 1
2020-05-16Disclaimer
This article is originally based on my understanding of this concept. No guarantee on the accuracy.๐
Starting from a puzzle from this article:
1 | doSomething().then(function () { |
How would this code run?
To answer this puzzle, a few key points should be understood:
.then(callback) would ounly be put into the task queue when the chained promise was settled (fullfulled/resolved or rejected).
.then(callback) would pass the value returned from the callback to following .then/.catch
If there is no explicit return of the callback, returns undefined
If the callback returns a promise as well, the following .then()/.catch() would be thrown into the task queue, when itโs settled. After the current stack is cleaned, they would be pushed to the stack (run the callback). Even a promise has already settled, the .then() still runs asynchronously.
let p = Promise.resolve('resolved already') p.then(v=>{console.loe('async result: '=v)}) console.log('cleaning stack') //print 'cleaning stack' 'async result: resolved already' <!--๏ฟผ1-->
if the callback returns a normal variable, the variable would be passed, and the state will be set to resolved.
a corner-case: if the callback returns obj which has a โthenโ method, the following then() would run as the code in โthenโ method.
Promise.resolve({value: 1, then: function (resolve) { //the following then call this function console.log(this.value) //print 1. resolve('then method in object') //resolve (or reject) function is a must๏ผotherwise the following then would not be called, pending }) .then(value => { console.log('the result from pre .then:' + value); //print 'the result form pre .then: then method in object' } }) <!--๏ฟผ2-->
But actually this is against the design of Promise whose aim is to avoid callback style but to chain the async exceutor outside the previous one. So itโd better update to this:
Class-based local storage
2020-05-13Class-based local storage
Sometimes when I was trying to build some small app, itโs really not neccessary to connect the app to the cloud database like mongoDB.
A local json file would be enough.
It provide basic CURD api. And it also allows customed repo by extending a new class from it.
1 | //using node modules |
A user repo:
A visual way to learn Closure
2020-04-29Disclaimer
This article is originally based on my understanding of this concept. No guarantee on the accuracy.๐
The closure is a kind of intimidating concept for people new to javascript.
I think itโs necessary to clarify some concept of execution context (EC) and scope before approaching โclosureโ itself.
Javascript has 3 types of scope (after ES6)
block scope
1
2
3
4{
let a = 0;
}
console.log(a) // ReferenceError: a is not definedFunction scope
Global scope
whenever youโre trying to call/use a variable, the engine would find it along the scope chain.
If the engine detects that a variable would not be called after the function execution context was removed from the call stack, it would junk the variable (garbage collecting) and free the memory.
The [[scope]] is determined during function declarartion.
All code is executed in their execution context: global EC or function EC.
EC can be abstracted as an object which includes variable object, scope chain, and this value.
Whenever a function is called, its EC would be pushed to the top of the call stack. And all the VO are activated as activation objects. When all the code inside the function is executed or returned, the EC was destroyed. Next time if the same function is called again, a new EC would be created.
The function EC has two phases: creation phase and execution phase.
The creation phase is when the VO and โthisโ are created, and the scope chain is initialed by [[scope]]
The execution phase is when the value of each object/variable is assigned and determined.