Last active
March 23, 2016 22:05
-
-
Save johntran/f2817dded2b9934dc208 to your computer and use it in GitHub Desktop.
No for or while loops.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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