Last active
November 23, 2016 12:07
-
-
Save venil7/dc948233d8011f4becba56be71e48b2c to your computer and use it in GitHub Desktop.
recursive, functional dropWhile & sort
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
| const dropwhile = (predicate, list) => { | |
| return list.reduce((acc, item) => { | |
| if (acc.drop) { | |
| const drop = predicate(item); | |
| const list = drop ? acc.list : [...acc.list, item]; | |
| return { drop, list }; | |
| } | |
| return {drop: false, list: [...acc.list, item]} | |
| }, {drop: true, list: []}).list; | |
| }; | |
| const dropwhile2 = (pred,list) => { | |
| const dw = (l) => { | |
| if (!l.length) return l; | |
| const [item, ...rest] = l; | |
| if(pred(item)) { | |
| return dw(rest); | |
| } | |
| return l; | |
| }; | |
| return dw(list); | |
| }; | |
| const sort = (unsorted) => { | |
| const insert = (n, array) => { | |
| if (!array.length) return [n] | |
| const [x, ...xs] = array; | |
| if (n <= x) { | |
| return [n,...array]; | |
| } | |
| return [x, ...insert(n, xs)]; | |
| }; | |
| const walk = (a, b = []) => { | |
| if (!a.length) return b; | |
| const [x, ...xs] = a; | |
| return walk(xs, insert(x, b)); | |
| }; | |
| return walk(unsorted); | |
| }; | |
| console.log(sort([7,3,6,1,8,4,2,5])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment