Skip to content

Instantly share code, notes, and snippets.

@timoxley
Last active June 7, 2016 07:27
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save timoxley/a34546c28c92025d040a391400ba5eb7 to your computer and use it in GitHub Desktop.
Save timoxley/a34546c28c92025d040a391400ba5eb7 to your computer and use it in GitHub Desktop.
JS Pop Quiz: How well do you know your functions?

JS Pop Quiz: How well do you know your functions?

Given an Array of Functions fns, what argument(s) can you pass to fns.forEach such that each function in fns will execute, in order, without creating any anonymous (or named) functions or invoking the Function constructor?

Conditions

  • Do not use the function keyword, or arrow functions () => .
  • Do not invoke the Function constructor.
  • Do not use method definitions.
  • Function#bind & friends on the Function.prototype are ok.
  • Answer should be a single line.
  • Try for clarity of concept rather than fewest characters; Reduce prototypical lookup to an absolute minimum.
  • Create no variables nor use any flow control structures i.e. no loops.
  • No Asynchrony (?!)
  • No unnecessary semicolons (just because)

Once you have a solution that works, make sure you can explain exactly why it works, and why your previous solutions didn't work.

Hint

Please don't post answers here (or in reply to the original tweet)

Do feel free to tweet them at me https://twitter.com/secoif

// the array of functions
const fns = [
function () {
console.log(1)
},
function () {
console.log(2)
},
function () {
console.log(3)
}
]
const call = // ??? your implementation here. Do not use the `function` keyword or arrow functions.
fns.forEach(call) // change this line if you like
// Expected console output should be
// 1
// 2
// 3
@bassjacob
Copy link

Should we be leaving answers here, or would that spoil the fun?

@timoxley
Copy link
Author

@subshad yep, I think that would spoil the fun. You can tweet them at me on twitter.

@Lucifier129
Copy link

@unlight
Copy link

unlight commented May 17, 2016

@lewisje
Copy link

lewisje commented May 17, 2016

@Lucifier129 came to the same conclusion I did, but I was inspired by its use in es6-shim; also, this old jsPerf comparison is relevant.

@timoxley
Copy link
Author

@unlight had not seen that before. Good explanation there.

@AlexanderZeilmann
Copy link

Since this solution didn't come up so far, I thought I post it.

@kirilloid
Copy link

Similar technique can be used to transform methods working on this like String#toUpper into a function from normal argument.
Look ma, point-free! https://en.wikipedia.org/wiki/Tacit_programming

@emirotin
Copy link

@razodactyl
Copy link

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