Skip to content

Instantly share code, notes, and snippets.

@mpatel3
Last active January 31, 2022 16:48
Show Gist options
  • Save mpatel3/7cc9a221c236750a3700067cc7a2ec3f to your computer and use it in GitHub Desktop.
Save mpatel3/7cc9a221c236750a3700067cc7a2ec3f to your computer and use it in GitHub Desktop.

Debouncing implementation

// as long as it continues to be invoked, it will not be triggered

function debounce (func, interval) {
  var timeout;
  return function () {
    var context = this, args = arguments;
    var later = function () {
      timeout = null;
      func.apply(context, args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, interval || 200);
  }
}

Throttling implementation

function throttle (func, interval) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function () {
      timeout = false;
    };
    if (!timeout) {
      func.apply(context, args)
      timeout = true;
      setTimeout(later, interval)
    }
  }
}

Usage

var myHeavyFunction = debounce(function() {
  // do heavy things
}, 250);
window.addEventListener('mousemove', myHeavyFunction);

Own Map Function

const sample = [1,2,3];
const mapResult = sample.map(function(val, index, array) {
    console.log('val :', val, 'index :', index, 'array :', array);
    return (val * 2);
});

Array.prototype.mymap = function(callback) {
    const resultArray = [];
    for (let index = 0; index < this.length; index++) {
        resultArray.push(callback(this[index], index, this));
    }
    return resultArray;
}

sample.mymap(function(val, index, arr) {
  return val*2;
});

Own Filter Function

let arr = [1, 2, 3, 4, 5];
const oddArr = arr.filter((num, index, array) => num % 2 === 0);
console.log(oddArr); // prints [2, 4]

Array.prototype.myFilter = function(callback) {
 const resultArray = [];
 for (let index = 0; index < this.length; index++) {
  const result = callback(this[index], index, this);
  if(result) {
    resultArray.push(arr[i]);
  }
 }
 return resultArray;
}

Own Reducer Function

let arr = [1, 2, 3, 4];const sumReducer = (accumulator, currentValue, index ,array) => accumulator + currentValue;
const sum = arr.reduce(sumReducer);console.log(sum);

Array.prototype.myReducer = function(callback, initialValue) {
  let accumulator = initialValue === undefined ? 0 : initialValue;
  for(let i=0; i < this.length; i++) {
    accumulator = callback(accumulator, this[i], i, this);
  }
  return accumulator;
}

Flatten javascript objects into a single-depth object

var flattenObject = function(ob) {
	var toReturn = {};
	
	for (var i in ob) {
		if (!ob.hasOwnProperty(i)) continue;
		
		if ((typeof ob[i]) == 'object') {
			var flatObject = flattenObject(ob[i]);
			for (var x in flatObject) {
				if (!flatObject.hasOwnProperty(x)) continue;
				
				toReturn[i + '.' + x] = flatObject[x];
			}
		} else {
			toReturn[i] = ob[i];
		}
	}
	return toReturn;
};
const data = {
    name: 'test',
    config: { },
    prev: { name: 'test1.1',
        config: { },
        prev: {
            name: 'test1.1.1',
            config: {  },
            prev: { name: 'test1.1.1.1', config: { }, prev: undefined }
        }
    }
};

function flatten (data) {
  let result = [];
  
  while (data) {
    result.push({ name: data.name, config: data.config });
    data = data.prev;
  }
  
  return result;
}

console.log(flatten(data));

// get only names
const res = flatten(data).map(el => el.name);
console.log(res);
var data = {
    name: 'test',
    config: { },
    prev: {
        name: 'test1.1',
        config: { },
        prev: {
            name: 'test1.1.1',
            config: {  },
            prev: {
                name: 'test1.1.1.1',
                config: { },
                prev: undefined
            }
        }
    }
};

var reduced = flatten(data, function(item) {
    return { name: item.name, config: item.config };
});

print(reduced.map(function(item) { return item.name }).join(', '));
 
function flatten(data, reducerFn, result) {
    result = result || [];
    if (data === undefined) return result;
    return flatten(data.prev, reducerFn, result.concat([reducerFn(data)]));
}

XHR Example

function reqListener () {
  console.log(this.responseText);
}

var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();

Promise

var asyncOperation = function(time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      resolve(time);
    }, time);
  });
}

var promisesToMake = [asyncOperation(2000), asyncOperation(1000), asyncOperation(3000)];
var promises = Promise.all(promisesToMake);
promises.then(function(results) {
 console.log(results);
});

output: [2000, 1000, 3000]

own promise.all function

var promiseAll = function(promises) {
  var results = [];
  var completedPromises = 0;
  return new Promise(function (resolve, reject) {
    promises.forEach(function(promise, index) {
      promise.then(function (value) {
        results[index] = value;
        completedPromises += 1;
        if(completedPromises === promises.length) {
          resolve(results);
        }
      }).catch(function (error) {
        reject(error);
      });
    });
  });
}

var promisesToMake = [asyncOperation(2000), asyncOperation(1000), asyncOperation(3000)];
var promises = promiseAll(promisesToMake);
promises.then(function(results) {
 console.log(results); // [2000, 1000, 3000]
});

// Adding support for reject. 

var asyncOperation = function(time) {
  return new Promise(function (resolve, reject) {
    setTimeout(function() {
      if(time === 2000) {
        reject("error at 2000");
      }
      resolve(time);
    }, time);
  });
}

var promisesToMake = [asyncOperation(2000), asyncOperation(1000), asyncOperation(3000)];
var promises = promiseAll(promisesToMake);
promises.then(function(results) {
 console.log(results);
}).catch(function(error) {
  console.log(error);
});

VSCode JS

var name = "Hello"; 
(function() { 
  var surname = " World"; 
  alert(name + surname); 
})(); 
alert(name + surname);
const promise = new Promise((resolve, reject) => {
    reject(Error('error occured'));
})
.then(error => console.log(error))
.catch(error => console.log(error))
.then(error => console.log(error));
var arr = [20, 56, 30, 40];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('index ' + i + ' number:' + arr[i]);
  }, 2000);
}
const arr = [20, 56, 30, 40];
for (var i = 0; i < 4; i++) {
  console.log(i);
  setTimeout(() => console.log(i+2), 3000); 
  console.log(i+1);
  setTimeout(() => console.log(i-1) , 0);
}
// output
// 0 1 1 2 2 3 3 4...3 times 3 and 3 times 6
// 0 1 1 2 2 3 3 4... -1, 0, 1, 2, 2, 3, 4, 5
let num = 0;
(function immediate() {
  if (num === 0) {
    let num = 1;
    console.log(num);
  }
  console.log(num); 
})();
function testS() {
  console.log(name);
  console.log(lname);
  var name = 'Jon';
  let lname = 'snow';
}
testS();
// output
// undefined and referenceError [with let are not intialized. temporal dead zone]
const Circle = {
  radius: 15,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius,
};

console.log(Circle.diameter());
console.log(Circle.perimeter());

// 30 and NaN
let a = 3;
let b = new Number(3);
let c = 3;

console.log(a == b); // true
console.log(a === b); // false
console.log(b === c); // false

function GOT(fName, lName) {
  this.fName = fName;
  this.lName = lName;
}

const g1 = new GOT('John', 'Snow');
const g2 = GOT('John', 'doe');

console.log(g1);
console.log(g2);

What are the three phases of event propagation?

/*
Capturing > Target > Bubbling
During the capturing phase, the event goes through the ancestor elements down to the target element. 
It then reaches the target element, and bubbling begins
*/
let number = 0;
console.log(number++);
console.log(++number);
console.log(number);
(() => {
  let a1=1,a2=2;
  console.log(++a2);
  console.log(a1++);
  console.log(a1);
  try {
    throw new Error();
  } catch (a1) {
    a1 = 1;
    a2 = 2;
    console.log(a1);
  }
  console.log(a2);
  console.log(a1);
})();
var d = [
  {key: 'key1', value: 'value1'},
  {key: 'key1', value: 'value2'},
  {key: 'key2', value: 'value3'},
  {key: 'key3', value: 'value4'},
  {key: 'key2', value: 'value5'},
]

var d = [
  {key: 'key1', value: ['value1', 'value2']},
  {key: 'key2', value: ['value3', 'value5']},
  {key: 'key3', value: ['value4']},

]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment