Skip to content

Instantly share code, notes, and snippets.

@timurcatakli
Created January 26, 2018 01:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timurcatakli/45642f38ba265d1305034a8c84fda0df to your computer and use it in GitHub Desktop.
Save timurcatakli/45642f38ba265d1305034a8c84fda0df to your computer and use it in GitHub Desktop.
// Dhruven
// In the interview, I put myself in a rabbit hole
// with no possible solution
//
// What I was trying to do is to pass the arguments from the first
// function to the second function.
//
// The problem is the second function is return as a value
// therefore it is an independent function and there is no way for it to accept
// a value... The value needs to be passed as an argument by the executed function
//
// if you see below testFunC takes arguments and they are spread as
// 'input'
// the returned function can not accept first functions arguments as an argument
// that is why we have to use closure
//
// closure lets us remember the first functions variables and then pass them
// to the second returned function
function testFunC(...input) {
const args = input
return function(a, args) {
console.log(args) // returns undefined
return a
}
}
const fnTestFunC = testFunC(6)
console.log(fnTestFunC(5))
// Using closure we can pass the arguments like below
function testFunD(input) {
const b = input
return function(a) {
console.log(b) // returns 6
return a + b // returns 11
}
}
const fnTestFunD = testFunD(6)
console.log(fnTestFunD(5))
// ----------------------------
const obj = {
a: 1,
b: 2
}
function testFunE() {
return this.a + this.b
}
console.log(testFunE()) // returns NaN
console.log(testFunE.bind(obj)()) // returns 3
// if we come back to what I was trying to do in the interview
// I was binding a function to an object and then executing it and
// assigning the returned value (which is a function) to a variable and
// then executing that variable with new parameters.
// below is how it shoould be done, the way I was trying was impossible as arguments
// can only be set by the executing function.
const objF = {
a: 1,
b: 2
}
function testFunF(...argsF) {
const initialArgs = argsF
const sum = this.a + this.b
return function(a, b) {
console.log(initialArgs)
return a + b + sum + initialArgs[0] + initialArgs[1]
}
}
const funTestFunF = testFunF.bind(objF)(3, 4)
console.log(funTestFunF(5, 6)) // returns 21
// I hope this explains why I was confused...
// Thanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment