Skip to content

Instantly share code, notes, and snippets.

@johntran
Last active March 23, 2016 22:05
Show Gist options
  • Save johntran/f2817dded2b9934dc208 to your computer and use it in GitHub Desktop.
Save johntran/f2817dded2b9934dc208 to your computer and use it in GitHub Desktop.
No for or while loops.
// pushOne(10,[]) results in [1,2,3,4,5,6,7,8,9,10]
// Imperative Programming
function pushOne(max, indexes) {
while (indexes.length < max) {
indexes.push(indexes.length+1)
}
return indexes
}
// Functional, Declarative Programming
function pushOne(max, indexes) {
const newIndexes = [...indexes, indexes.length+1]
return indexes.length < max ? pushOne(max, newIndexes)
: newIndexes
}
// One Liner
const pushOne = (max, indexes) => indexes.length < max ?
pushOne(max, [...indexes, indexes.length+1])
: indexes
/**
* The second one is doing the first function in a functional/immutable way
* This is how one would program it in Elixir or Haskell.
* They both run at the same speed. Its just different philosophies.
* I prefer not using for-loops at all.
**/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment