Skip to content

Instantly share code, notes, and snippets.

@azemetre
Last active August 30, 2019 19:52
Show Gist options
  • Save azemetre/9aaad96300978a6005baaf596ffb6455 to your computer and use it in GitHub Desktop.
Save azemetre/9aaad96300978a6005baaf596ffb6455 to your computer and use it in GitHub Desktop.
JS Qs
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
var myEfficientFn = debounce(function() {
// All the taxing stuff you do
}, 250);
window.addEventListener('resize', myEfficientFn);
// higher-order function that takes an array as input and returns a reducer
// a reducer function (a pure fn, same input = same output) takes the previous state
// and an action, and then returns the next state
// referred to as a reducer because you pass to Array.prototype.reduce
// const reducer = (accumulator, currentValue) => accumulator + currentValue
const flatten = (arr) => {
const reducer = (flat, toFlatten) => {
return flat.concat(Array.isArray(toFlatten) ? flatten(toFlatten) : toFlatten);
};
return arr.reduce(reducer, []);
}
const arrStrInt = [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];
const arrNested = [[[1, [1.1]], 2, 3], [4, 5]];
const arrInsane = [[1,[2,[[3]]]],4,[5,[[[6]]]]];
const arrObj = [
{
id: 1,
country: [
{
id: "5a60626f1d41c80c8d3f8a85"
},
{
id: "5a6062661d41c80c8b2f0413"
}
]
},
{
id: 2,
country: [
{
id: "5a60626f1d41c80c8d3f8a83"
},
{
id: "5a60626f1d41c80c8d3f8a84"
}
]
}
];
console.log(flatten(arrStrInt))
console.log(flatten(arrNested))
console.log(flatten(arrObj))
console.log(flatten(arrInsane))
implicit binding
explicit binding uses call, bind, or apply
bind returns a new function instead of immediately invoking it
new Binding
using the keyword
Lexical binding
window binding
the global object
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment