Home

JS trickery

I like the concept of preconditions in the Eiffel programming language. Here is a way to do it succinctly in JS


/**
* throws an error if the requirement function returns false
* @param {() => boolean} requirement (has to be named function)
*/
const require = requirement => {
  if(requirement() === false){
    throw new Error(`Requirement not satisfied: ${requirement.name}`)
  }
}

export const add_colleague = colleague => project => {
  require(function colleague_is_assigned_to_a_team() {
	return 'team' in colleague
  })
  require(function project_has_team_assigned() {
    return 'team' in project
  })
  require(function colleague_is_in_a_project_team() {
	return colleague.team.id === project.team.id
  })
  // main logic of the app
}