Skip to content

Instantly share code, notes, and snippets.

@venil7
Last active November 23, 2016 12:07
Show Gist options
  • Save venil7/dc948233d8011f4becba56be71e48b2c to your computer and use it in GitHub Desktop.
Save venil7/dc948233d8011f4becba56be71e48b2c to your computer and use it in GitHub Desktop.
recursive, functional dropWhile & sort
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