Logical Approach to Common Problems — Part 2

📄 Table of contents

➤ Misc

`this’ exercise

setTimeout() Exercise

Write a JavaScript program to find the most frequent item of an array. Search should be case insensitive.input: [1, 'T', 'a', 'T', 2, 3, 'T', 3, 't', 2, 't', 9, 3];
output: t = 5
Attach a function to array in js?
let tempArray = [6, 2, 3, 4, 5];
let averageValues = tempArray.average();
console.log(averageValues); // should return average of tempArray

◉ sum of no.s using Recursion

var array_sum = function(arr) {
if (arr.length === 1) {
return arr[0];
}
return arr.pop() + array_sum(arr);

};
console.log(array_sum([1,2,3,4,5,6]));# 21

The first approach utilizes a for-loop which again is not entirely functional so it is replaced with the recursive function addRecursively(). Like the for-loop which operates on an array, the recursive function takes in an array of numbers and begins adding the first to the subsequent one. It also establishes a base case of returning 0 if all the numbers have been added, which is checked by assessing if the array of numbers length is 0.

a programming paradigm is how code is implemented and executed,, and in the case of OOP, it is via the use of classes and objects.

the functional programming paradigm approach is the ability for functions to be versatile, and JavaScript accomplishes that by making functions first-class members. This means that functions can be used as data, and passed around within a program, such as when stored within variables, data structures like array or objects, passed as arguments to other functions, or returned from function calls. It is one that is gaining popularity, as it is seen extensively within React and other libraries.

approach is the ability for functions to be versatile, and JavaScript accomplishes that by making functions first-class members. This means that functions can be used as data, and passed around within a program, such as when stored within variables, data structures like array or objects, passed as arguments to other functions, or returned from function calls.

In conclusion, these key concepts, the immutability of data, pure functions, higher-order functions, recursion, and composition, create the foundation for functional programming.

pure functions which state that functions should compute a return value based solely on the arguments it receives and should not cause side effects.

// functional approach
const log = message => console.log(message);

Taking a look back at the first example, the log() function is not a pure function. It causes the side effect of logging to the console while returning a value, undefined, that is not computed by its “message” argument. And because pure functions return values are based on their arguments, they are predictable and easy to implement tests for.

const increaseByOne = num => num + 1;const num = 1
const newNum = increaseByOne(num) // => 2
console.log(num) // => 1

Functions that accept functions as arguments or return functions are known as higher-order functions and are another key concept of functional programming.

const sum = (a,b) => a + b
const average = (fn, ...nums) => nums.reduce(fn) / nums.length;
const numsAvg = average(sum, 1, 2, 3) // => 2

In this example, two pure functions are defined sum() and average(), which take in some arguments, and do not mutate the arguments but compute a return value based on them. The average() function is a higher-order function that takes in a function, sum(), as an argument and computes a return value by passing it into another higher-order function, reduce(), as the reducer. Next, an arbitrary amount of numbers are passed to the rest parameter and aggregated into a “nums” array. Finally, the array of numbers are reduced and divided by the total amount of numbers passed into the average() function to return the average.

◉ sum of (numbers) when you don’t know how many numbers are there…rest operator.

const sum = (...args)=>{
return args.reduce((a, b) => a+b);
}
console.log(sum(2,3,4,6));
# 15

(…) Rest parameter syntax

function numbers(x,y, ...z){
console.log(x,y,z);
}
numbers(1,2,3,4,5,6);
# Output:
1
2
[3,4,5,6]

(…) Spread parameter syntax

function getSum(x, y, z){
console.log(x+y+z);
}
let arr = [10,20,30];
getSum(...sumArray);

Q. increment the counter on each page load

This is a very simple example showing a counter that will increment by one every time you reload a a page. As the counter is saved in your own browser and it is associated with the site you visited, this number will be independent of what other people see, or what you’ll see if you visit the same page using a different device or even a different browser on the same device.

for more read @ https://code-maven.com/on-load-counter-with-javascript-and-local-storage

◉ Chaining in JS (as in jQuery)

  1. create an object literal
  2. attach methods to object literal
  3. update this.result in each function and return this

◉ Get all possible substrings of a given string

all possible substrings of a given string

◉ Find a value in an array of objects in JS

sum(10)(2)(3)(4)()

Sum using Recursion

Don’t Use If-Else and Switch in JavaScript, Use Object Literals

We are selecting the calculation we want to do and executing the response, passing the two numbers. You can use optional chaining (the ?. in the last line of code) to only execute the response if it is defined. Otherwise, fall through to the default return string.

for more @https://betterprogramming.pub/dont-use-if-else-and-switch-in-javascript-use-object-literals-c54578566ba0

◉ “this” keyword in js

It has different values depending on where it is used:

  • In a method, this refers to the owner object.
  • Alone, this refers to the global object.
  • In a function, this refers to the global object.
  • In a function, in strict mode, this is undefined.
  • In an event, this refers to the element that received the event.
  • Methods like call(), and apply() can refer this to any object.

Note that I’m calling the walk method in this case, which is inside of the object.

  • But when we apply some slight changes, different results were obtained. We added another const named as newWalk which gives reference to the walk method in the user object. For simplicity, we can say newWalk is a function that calls the walk method in the user object.
  • This time we if we call the newWalk method by giving a reference to another method (walk) then most likely you will obtain undefined on the console. (Note that in my case we obtained a window object as I’m running this code in a React Project with Strict Mode disabled).

4. Binding this

For example,

  • In the previous example where we aren’t able to access the user object using the this keyword, using the bind method you can solve all of that issues quickly.
  • We just have to pass .bind(an object that you want to give reference) to your function & we longer have to work with an undefined or window object, because the this keyword now always give reference the user object

◉ “this”

var foo = {
name: "anil",
age: 30
};
function getDetails() {
return (this.name + " is + this.age + " yrs old.");
}
foo.logMyDetails = getDetails;
console.log(foo.logMyDetails());
//anil is 30 yrs old.
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
function Employee(name) {
this.name = name;
this.getName = function () {
return this.name;
}
}
var e1 = new Employee(“anil");
e1.getName();
#anil
▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
function Employee(name) {
this.name = name;
}
Employee.getName = function () {
return this.name;
}
var e2 = new Employee("kumar");
e2.getName(); #TypeError
var e3 = e2.getName;
console.log(e3()); #TypeError
var e4 = e2.getName.bind(e2);
console.log(e3()); #TypeError ▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬▬
var x = "outermost";
var foo = {
x: "inner",
baz: {
x: "innermost",
bar: function () {
return this.x;
}
}
}
var go = foo.baz.bar; # "this" refers to global object
console.log(go());
console.log(foo.baz.bar())# outermost
# innermost

◉ What happens to ‘this’ in a function nested inside a method of an object?

Explanation: splitName() is a REGULAR function inside setName() but not directly bind to profile object. So, it sets “this” to `window` object, which doesn’t have a firstname property, , and hence the NaN outputs are obtained.

How do we solve this issue?

[1]. One solution is to assign the this value from the outer function to a variable to be used in the nested function like so:

var self = this;

[2]. Second solution to this problem involve using bind(), call() or apply().

[3]. Thirdly, converting it to fat arrow function, splitName=()=> function looses its “this” and gets value of this from enclosing body which is profile over here.

Explanation:

this.value refers to the value property in the ‘object’ object.

And add method has a parameter called val and number functions takes that as a parameter and return val * this.value, but this.value in the number functions is undefined and 10 * undefined is equal to NaN. So, the answer is 20 , NaN.

Output : 5,NaN, 5

◉ `this` inside Classes

◉ setTimeout() Exercise:

console.log("1");
console.log(“2");
setTimeout(function () {
console.log("3")
}, 0);
var promise = new Promise((resolve, reject) => {
resolve(‘Promises -resolved‘);
})
promise.then(function (successMessage) {
console.log(successMessage);
}, function (errorMessage) {
console.log(errorMessage);
})
console.log(“4");
# (same result in chrome & firefox)
“1”
“2”
“4"
'Promises -resolved’
“3”

The reason is because `let` is block scoped. What that means is that scope of a variable declared using `let` is on a block level, hence for each block of code, a new memory address is assigned to variable. Hence, each of the setTimout will log the value of the variable at that point in the loop.

But with `var` (which is globally scoped). The variable i retains it’s memory location(new memory locations are not assigned). For this reason , all the setTimout function are going to log the content of same memory location, unfortunately the value of i increases until the exit value 3. Hence all the setTimout functions will log 3. That’s you have 3 3 3 when it is var.

Getting key with the highest value from object

var obj = {a: 1, b: 2, undefined: 1};Object.keys(obj).reduce(function(a, b){ return obj[a] > obj[b] ? a : b });

Q. find the most frequent item in an array

Write a JavaScript program to find the most frequent item of an array. Search should be case insensitive.input: [1, 'T', 'a', 'T', 2, 3, 'T', 3, 't', 2, 't', 9, 3];
output: t = 5

Add a method to Array object in Javascript?

var arr = [2,3,4,5];
arr.methodName = function() { alert("Array method."); }
arr.methodName();

Chaining ( as in jQuery)

Experience with Front-end Technologies and MERN / MEAN Stack. Working on all Major UI Frameworks like React, Angular.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store