ES6 - Intention Revealing Pure Functions

by Cristi Salcescu

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore.js"></script>

JavaScript

const todos = createTodos();
const users = createUsers();

const newTodos =  todos
							.filter(isTopPriority)
              .map(_.partial(toTodoView, users))
              .sort(ascByUserName);
console.log(newTodos);

//named pure functions
function isTopPriority(todo){
  return !todo.completed && todo.type === "RE";
}

function toTodoView(users, todo){
  return {
    title : todo.title,
    userName : users[todo.userId].name
  }
}

function ascByUserName(todo1, todo2){
  return todo1.userName.localeCompare(todo2.userName);
}
  


//functions that generate sample data
function createUsers(){
  return {
    1 : { name : "User1"},
    2 : { name : "User2"},
    3 : { name : "User3"}
  };
}

function createTodos(){
  return [
    { 
      id : 1,
      type : "NC",
      title : "This is title 1",
      userId : 1,
      completed : true
    },
    { 
      id : 2,
      type : "RE",
      title : "This is title 2",
      userId : 2,
      completed : false
    },
    { 
      id : 3,
      type : "RE",
      title : "This is title 3",
      userId : 3,
      completed : false
    }
  ];
}