Skip to content

Instantly share code, notes, and snippets.

@angus-c
Last active August 30, 2018 19:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save angus-c/10994881 to your computer and use it in GitHub Desktop.
Save angus-c/10994881 to your computer and use it in GitHub Desktop.
/*
sayIt accepts an unlimited number of chaining calls, each passing a word. When it's finally called
without arguments, all the passed words are printed in order
sayIt('have')('you')('got')('any')('fish')('fingers?')(); ->
"have you got any fish fingers?"
A regular implementaion would go sthg like this
function sayIt(firstWord) {
var words = [];
return (function reallySayIt(word) {
if (word) {
words.push(word);
return reallySayIt;
} else {
return words.join(' ');
}
})(firstWord);
}
During a bout of insomnia last night, I wondered if I could write it without any conditionals.
Here's what I got.
WARNING: IT'S MAD
*/
var sayIt = function(word) {
var words = Array.prototype;
words.push(word);
sayIt.toString = function() {
try {return words.join(' ')} finally {words.splice(0, words.length);}
}
return sayIt;
}
@WebReflection
Copy link

Bind All The Things

var sayIt = function(word){
  this.push(word);
  sayIt.toString = function () {
    return this.splice(0, this.length).join(' ');
  }.bind(this);
  return sayIt;
}.bind([]);

@brycebaril
Copy link

function sayIt() {
  var words = [].slice.call(arguments, 0).join(" ")
  try { words.length > arguments[0].length && arguments[1].length }
  catch (e) { return words }
  return function(word) {
    return sayIt.call(null, words, word)
  }
}

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