项目作者: Front-End-Hour

项目描述 :
Frontend Hour is one hour learning everyday. This is a collection of all major frontend (mainly Adv JavaScript) concepts that will take you from Novice frontend Engineer to Nijna.
高级语言: JavaScript
项目地址: git://github.com/Front-End-Hour/frontend-hour.git
创建时间: 2020-10-06T15:21:22Z
项目社区:https://github.com/Front-End-Hour/frontend-hour

开源协议:

下载


FRONTEND HOUR

Frontend Hour

Frontend Hour is a concept of one hour learning Everyday. This Repository is a collection of all the major Frontend Concepts.

Concepts

  1. Array Methods
  2. Async Await
  3. Bind Polyfill
  4. Call, Apply, Bind
  5. Class, Class Extending
  6. Closure
  7. Collections
  8. Currying
  9. Debounce
  10. Destructuring
  11. Event Loop
  12. Extends with/without new
  13. Function Composition
  14. Hoisting
  15. Interators and Generators
  16. Object Oriented Javascript
  17. Promises
  18. Promisfy
  19. Prototype Chain
  20. Recursion
  21. Temporal Dead Zone
  22. Throttle
  23. Value and Reference
  24. Basic Design Paterns

Algorithms

  1. Basics
  2. Bubble Sort
  3. Insertion Sort
  4. Merge Sort
  5. Quick Sort

Problems

  1. Array Flat
  2. Array Unique value
  3. Coercion Problem
  4. Get By Path
  5. Longest String
  6. Move Element
  7. Number Pairs
  8. Scope Problem
  9. Shared Numbers
  10. Sleep
  11. Small Tricky Interview questions
  12. This Keyword

Function Composition

Function composition is the process of combining two or more functions to produce a new function.
Composing functions together is like snapping together a series of pipes for our data to flow through.
Put simply, a composition of functions x and y can be defined as z(y(z)), which evaluates from the inside out — right to left.
In other words, the evaluation order is: z, y, x

  1. let reduceArray = [1, 2, 3];
  2. reduceArray.reduce((input, item) => {
  3. console.log(`input: ${input}, item: ${item}`);
  4. return input + item;
  5. }, 11);
  6. function addTwo(num) {
  7. return num + 2;
  8. }
  9. function divideByFive(num) {
  10. return num / 5;
  11. }
  12. function multiplyByFour(num) {
  13. return num * 4;
  14. }
  15. let m1 = multiplyByFour(divideByFive(addTwo(3)));
  16. console.log(
  17. 'Function composition for `((x + 2) / 5) * 4` with `x` of 3 is:',
  18. m1
  19. );
  20. let a = [addTwo, divideByFive, multiplyByFour].reduce((input, fun) => {
  21. return fun(input);
  22. }, 3);
  23. console.log('Function Composition for same using Array reduce - ', a);

Closure

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).
In other words, a Closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.
To use a closure, define a function inside another function and expose it. To expose a function, return it or pass it to another function. The inner function will have access to the variables in the outer function scope, even after the outer function has returned.

  1. function closureTest() {
  2. var x = 2;
  3. return x;
  4. }
  5. console.log(closureTest()); // returns 2
  6. closureTest();
  7. // console.log(x); Functions local variable will not be available once the functions scope is closed.
  8. function testClosure() {
  9. var x = 2;
  10. function closeX() {
  11. return x;
  12. }
  13. return closeX;
  14. }
  15. console.log(testClosure());
  16. let testCloseX = testClosure(); // has closeX function definition
  17. console.log(testCloseX()); // 2
  18. function ticketBuilder(transport) {
  19. let passengerNo = 0;
  20. return function builder(name) {
  21. passengerNo++;
  22. console.log(
  23. 'Your ticket in ' +
  24. transport +
  25. ' welcomes ' +
  26. name +
  27. '! and your passenger no is ' +
  28. passengerNo
  29. );
  30. };
  31. }
  32. let getBusTicket = ticketBuilder('Bus');
  33. // Persistent Lexical scope reference data or Closed over variable environment
  34. // Consists of variable environment (arguments and variables) of ticketBuilder function.
  35. console.log(getBusTicket('Raghu'));
  36. console.log(getBusTicket('Chaitu'));
  37. console.log(getBusTicket('Raghu1'));

Iterators and Generators

An iterator lets you iterate through a collection’s contents one at a time, pausing at each item.
An iterator is any object that implements the iterator protocol by having a next() method that returns a value property and a done property.
Generator is also kind of iterator when called returns and interable that pipelines all the yeild values one after the other on every next call on the returned iterable.
yeild is like pause or temporary return form the function.

  1. function createIterator(array) {
  2. let count = 0;
  3. return function next() {
  4. let item = array[count];
  5. count += 1;
  6. return item;
  7. };
  8. }
  9. const names = ['a', 'b', 'c'];
  10. const namesIterator = createIterator(names);
  11. console.log(namesIterator);
  12. console.log(namesIterator());
  13. console.log(namesIterator());
  14. console.log(namesIterator());
  15. function* createFlow() {
  16. let x = 0;
  17. let y = 90;
  18. let result = x + y;
  19. yield `Frontend Hour ${result}`;
  20. const newNum = yield 'returnVal';
  21. const num = 10 + newNum;
  22. yield num;
  23. }
  24. const generatorFlow = createFlow();
  25. console.log(generatorFlow.next());
  26. console.log(generatorFlow.next());
  27. console.log(generatorFlow.next(10));
  28. console.log(generatorFlow.next());

async - await

async-await basically act as syntactic sugar on top of promises, making asynchronous code easier to write and to read afterwards.

The word async before a function means one simple thing: a function always returns a promise.
await, that works only inside async functions, await makes JavaScript wait until that promise settles and returns its result.
await literally suspends the function execution until the promise settles, and then resumes it with the promise result. That doesn’t cost any CPU resources, because the JavaScript engine can do other jobs in the meantime: execute other scripts, handle events, etc.

  1. /* This consists Examples for Promise,
  2. fetch, async and await using a fake api call.
  3. */
  4. var promise = new Promise(function (resolve, reject) {
  5. setTimeout(() => {
  6. if (false) {
  7. resolve('Frontend Hour');
  8. } else {
  9. reject(Error('It broke'));
  10. }
  11. }, 2000);
  12. });
  13. promise
  14. .then(function (result) {
  15. console.log(result); // "Stuff worked!"
  16. })
  17. .catch((err) => {
  18. console.log(err);
  19. });
  20. fetch('https://jsonplaceholder.typicode.com/todos/1')
  21. .then((response) => response.json())
  22. .then((json) => console.log(json));
  23. // Using generator functions
  24. function* createFlow() {
  25. console.log('Me First');
  26. const data = yield fetch('https://jsonplaceholder.typicode.com/todos/1');
  27. console.log(data);
  28. yield data.json();
  29. }
  30. const returnNextElement = createFlow();
  31. const futureData = returnNextElement.next();
  32. console.log('Me Second');
  33. let jsonData = {};
  34. futureData.value.then((response) => {
  35. jsonData = returnNextElement.next(response);
  36. jsonData.value.then((json) => console.log(json));
  37. });
  38. // async & await
  39. async function createFlow() {
  40. console.log('Me First Async');
  41. const data = await fetch('https://jsonplaceholder.typicode.com/todos/1');
  42. console.log(data);
  43. const json = await data.json();
  44. console.log(json);
  45. }
  46. createFlow();

Prototype Chaining

JavaScript objects are dynamic “bags” of properties (referred to as own properties). JavaScript objects have a link to a prototype object. When trying to access a property of an object, the property will not only be sought on the object but on the prototype of the object, the prototype of the prototype, and so on until either a property with a matching name is found or the end of the prototype chain is reached.

  1. // Problem
  2. let user1 = {};
  3. user1.name = "raghu";
  4. user1.score = 0;
  5. user1.incrementScore = function () {
  6. this.score += 1;
  7. }
  8. user1.printScore = function () {
  9. console.log(this.score);
  10. }
  11. let user2 = {};
  12. user2.name = "raghu";
  13. user2.score = 0;
  14. user2.incrementScore = function () {
  15. this.score += 1;
  16. }
  17. user2.printScore = function () {
  18. console.log(this.score);
  19. }
  20. // Solution
  21. function UserCreater(name, score) {
  22. let newUser = Object.create(userFunction);
  23. newUser.name = name;
  24. newUser.score = score;
  25. return newUser;
  26. }
  27. const userFunction = {
  28. incrementScore: function () {
  29. this.score += 1;
  30. },
  31. printScore: function () {
  32. console.log(this.score);
  33. }
  34. }
  35. const user1 = UserCreater('mc', 9);
  36. const user2 = UserCreater('raghu', 19);
  37. user1.incrementScore();
  38. // Solution using new keyword
  39. function UserCreater(name, score) {
  40. this.name = name;
  41. this.score = score;
  42. }
  43. UserCreater.prototype.incrementScore = function () {
  44. this.score++;
  45. }
  46. UserCreater.prototype.printScore = function () {
  47. console.log(this.score);
  48. }
  49. const user1 = new UserCreater('user1', 4);
  50. const user2 = new UserCreater('user2', 3);
  51. // Solution using class keyword
  52. class UserCreater {
  53. constructor(name, score) {
  54. this.name = name;
  55. this.score = score;
  56. }
  57. incrementScore() {
  58. this.score++;
  59. }
  60. printScore() {
  61. console.log(this.score);
  62. }
  63. }
  64. const user1 = new UserCreater('user1', 4);
  65. const user2 = new UserCreater('user2', 3);
Different ways to create objects and the resulting prototype chain
  1. With Object.create()
  2. With a constructor
  3. With a class keyword
  1. let user1 = {
  2. name: 'raghu',
  3. score: 3,
  4. printScore: function() {
  5. console.log(this.score);
  6. },
  7. incrementScore: function() {
  8. user1.score++;
  9. }
  10. }
  11. let user2 = {
  12. name: 'raghu',
  13. score: 3,
  14. printScore: function() {
  15. console.log(this.score);
  16. },
  17. incrementScore: function() {
  18. user2.score++;
  19. }
  20. }
  21. let user3 = {
  22. name: 'raghu',
  23. score: 3,
  24. printScore: function() {
  25. console.log(this.score);
  26. },
  27. incrementScore: function() {
  28. user3.score++;
  29. }
  30. }
  31. /*- --------------------------------------*/
  32. function createUser(name, score) {
  33. var newUser = {};
  34. newUser.name = name;
  35. newUser.score = score;
  36. newUser.printScore = function() {
  37. console.log(this.score);
  38. }
  39. newUser.incrementScore = function() {
  40. this.score++;
  41. }
  42. return newUser;
  43. }
  44. let user5 = createUser('raghu', 2);
  45. let user4 = createUser('myname', 2);
  46. /*- --------------------------------------*/
  47. function createUser(name, score) {
  48. var newUser = Object.create(userFunctionsStore);
  49. newUser.name = name;
  50. newUser.score = score;
  51. return newUser;
  52. }
  53. const userFunctionsStore = {
  54. printScore: function() {
  55. console.log(this.score);
  56. },
  57. incrementScore: function() {
  58. this.score++;
  59. }
  60. }
  61. let user6 = createUser('raghu', 99);
  62. let user7 = createUser('raghu7', 99);
  63. /*- --------------------------------------*/
  64. function createUser(name, score) {
  65. this.name = name;
  66. this.score = score;
  67. }
  68. createUser.prototype.printScore = function() {
  69. this.score++;
  70. }
  71. let user8 = new createUser('name', 99);
  72. let user9 = new createUser('name8', 99);
  73. class CreateUser {
  74. constructor(name, score) {
  75. this.name = name;
  76. this.score = score;
  77. }
  78. incrementScore() {
  79. this.score++;
  80. }
  81. printScore() {
  82. console.log(this.score);
  83. }
  84. }
  85. let user9 = new CreateUser('nnnn', 99);
  86. user9 = {
  87. name: 'nnnn',
  88. score: 99,
  89. __proto__: {
  90. incrementScore: function() {
  91. this.score++;
  92. },
  93. printScore: function() {
  94. console.log(this.score);
  95. }
  96. }
  97. }

Promisification

Promisification means transformation. It’s a conversion of a function that accepts a callback into a function returning a promise.

  1. // Problem
  2. setTimeout(() => {
  3. setTimeout(() => {
  4. setTimeout(() => {
  5. setTimeout(() => {
  6. setTimeout(() => {
  7. setTimeout(() => {
  8. console.log('needed data');
  9. }, 100);
  10. }, 100);
  11. }, 100);
  12. }, 100);
  13. }, 100);
  14. }, 100);
  15. Promise
  16. .then(cb)
  17. .then(cb)
  18. .then(cd)
  19. // Solution
  20. function promisify(fn) {
  21. return function (...args) {
  22. return new Promise((resolve, reject) => {
  23. function cb(response) {
  24. resolve(resolve);
  25. }
  26. fn.apply(this, [cb].concat(args));
  27. });
  28. }
  29. }
  30. let promisifySetTimeout = promisify(setTimeout);
  31. function printNames() {
  32. console.log('Second Call back called');
  33. }
  34. function printNameAndReturnPromise() {
  35. console.log('First Call back called');
  36. return promisifySetTimeout(1000);
  37. }
  38. promisifySetTimeout(2000)
  39. .then(printNameAndReturnPromise)
  40. .then(printNames);

Throttle

Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 1000 milliseconds.

  1. function throttle(fn, time) {
  2. let timeout;
  3. return function () {
  4. if (timeout) {
  5. return;
  6. }
  7. timeout = setTimeout(() => {
  8. fn.apply(this, arguments);
  9. timeout = null;
  10. }, time);
  11. }
  12. }
  13. function printName(name) {
  14. console.log(name);
  15. }
  16. const throttlePrintName = throttle(printName, 1000);
  17. // So, Throttling enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 1000 milliseconds.”
  18. function keyUpEvent(e) {
  19. throttlePrintName(e.target.value)
  20. }

Debounce

Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 1000 milliseconds have passed without it being called.”

  1. function debounce(fn, ms) {
  2. let timeoutId;
  3. return function () {
  4. if (timeoutId) {
  5. clearTimeout(timeoutId);
  6. }
  7. timeoutId = setTimeout(() => {
  8. fn.apply(this, arguments);
  9. }, ms);
  10. }
  11. }
  12. function printName(name) {
  13. console.log(name);
  14. }
  15. const debouncePrintName = debounce(printName, 1000);
  16. //So, Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 1000 milliseconds have passed without it being called.”
  17. function keyUpEvent(e) {
  18. debouncePrintName(e.target.value)
  19. }

Coercion

Type coercion is the automatic or implicit conversion of values from one data type to another (such as strings to numbers). Type conversion is similar to type coercion because they both convert values from one data type to another with one key difference — type coercion is implicit whereas type conversion can be either implicit or explicit.