JSFiddle - React, Tailwind, and code Playground
by Prathameshsb
HTML
<h1>
Flattern matrix, "this", closure, memoization, currying infinite, convert to curry fn
</h1>
<div>
<div class='parent'>
<div class='child'>
</div>
</div>
</div>
CSS
.parent {
background: #666;
height: 300px;
position: relative;
}
.parent > .child {
display: none;
position: absolute;
top: 0;
height: 100px;
width: 100px;
background-color: white;
}
.parent:hover > .child {
display: initial;
}
JavaScript
const matrix = [
[1, 2, 3, 4],
[5, 6, 7, 8],
[9, 10, 11, 12],
[13, 14, 15, 16]
];
function flatten(arr) {
return Array.isArray(arr) ? [].concat(...arr.map(flatten)) : arr
}
//console.log(flatten(matrix));
const obj = {
name: 'Billy',
sing: function() {
this.age = "20"
console.log('a', this);
var anotherFunction = function() {
this.age = "30"
console.log('b', this);
}
anotherFunction();
}
}
// obj.sing();
let view = 0;
function like() {
let called = 0;
return function() {
if (called > 0) {
return;
} else {
view = 'wohoo'
console.log('it is this -', view);
called++;
}
}
}
let check = like();
/* check();
check();
check();
check();
check();
*/
// memoization
function memoize(fn, context) {
const result = {};
return function(...args) {
let argsCache = JSON.stringify(args);
if (!result[argsCache]) {
result[argsCache] = fn.call(context || this, ...args);
}
return result[argsCache];
}
}
const clumsyProduct = (num1, num2) => {
for (let i = 0; i <= 100000; i++) {}
return num1 * num2
}
const mymemo = memoize(clumsyProduct);
// console.log(mymemo(20, 30));
// currying infinite
function sum(a) {
return function(b) {
if (b) {
return sum(a + b)
} else {
return a;
}
}
}
// console.log(sum(2)(3)(4)());
// convert f(a,b,c) into f(a)(b)(c);
function curry(func) {
return function curriedFunc(...args) {
if (args.length >= func.length) {
return func(...args)
} else {
return function(...next) {
return curriedFunc(...args, ...next);
}
}
}
}
const sum1 = (a, b, c) => a + b + c;
const totalSum = curry(sum1);
console.log(totalSum(1)(2)(3));