I’m trying to understand what this code is doing, it’s from a nodejs. I don’t understand what is this structure is doing
return({object}={})=>{more code}
you can find the repository here: https://github.com/howardmann/clean-node/blob/master/models/teacher/teacher.js
let buildMakeTeacher = function(teacherValidator) { return ({ name, subject, tenure = false } = {}) => { let {error} = teacherValidator({name, subject, tenure}) if (error) throw new Error(error) return { getName: () => name, getSubject: () => subject, isTenure: () => tenure } } }
Advertisement
Answer
In addition to answer by @Sarkar, the amount of curly braces here may shock you. The point of others (that don’t declare a scope) is object destructuring. Breaking down:
let {error} = teacherValidator({name, subject, tenure})
This line takes object returned by teacherValidator
and extracts a key named error
from it. If it returned, say, {error: 'Fail', errorcode: 1}
, then error
is assigned to 'Fail'
.
return ({ name, subject, tenure = false } = {}) => { doSomething(); }
This creates an anonymous function with complex argument handling. It is (by calling result, implementation should differ) equivalent to:
return function(params={}) { let {name, subject, tenure=false} = params; doSomething(); }
This function:
- When called without args, has params set to empty object;
- When called with argument, extracts
name
andsubject
keys from it (undefined
if not present) andtenure
key (false
if missing). - Performs some action with these args (checks error and returns object with 3 anonymous functions like getters)