2
\$\begingroup\$

I've been trying to get into functional programming with javascript and have tried to make some experiments with currying and function composition.

What I've played with so far is a sorter function that sorts object keys either ascending or descending:

const data = [
  { grade: 4, name: 'Zoe'},
  { grade: 3, name: 'River'},
  { grade: 9, name : 'Wash'},
  { grade: 8, name: 'Jayne'},
  { grade: 6, name: 'Inara'}
];


const ascending = (a, b) => a < b;

const descending = (a, b) => a > b;

const compare = fn => key => (a, b) => fn(a[key], b[key]) ? - 1
                                       : fn(b[key], a[key]) ? 1
                                       : 0

const sorter = (order, key) => {
  const orderFn = order === 'asc' ? ascending : descending;

  return compare(orderFn)(key)
}

const sortBy = (order, key) => fn => list => list.sort(fn(order, key))


const sorted = sortBy('asc', 'grade')(sorter)(data)
console.log(sorted)

JSBin link

Being that I'm very much new to functional programming and javascript in general, but looking to improve the quality and readability of my code, how could the program written above be improved?

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.