es6 syntax for factory - javascript

Could someone please explain how the following es6 code is a factory.
const createChat = ({
id = 0,
msg = '',
user = 'Anonymous',
timeStamp = 1472322852680
} = {}) => ({
id, msg, user, timeStamp
});

All the values you see (0, '', Anonymous, 1472322852680) are the default values. They would normally be extracted from the passed in object but if they don't exist these are what will be used in their place. This is default parameters.
The => ({...}) is shorthand to return the value (notice there is no return statement). So here it is returning an object with the passed in id, msg, user, and timeStamp unless those values aren't passed in. It is accomplishing this by using destructing.
https://jsfiddle.net/y7mb6jsp/

Related

Typescript interface objects to string array

i have a interface named UiDataUpdateFunction.In the code defined like this.
#Effect()
bulkCreateUIDataUpdateFunction$ = this.actions$.pipe(
ofType<UIDataUpdateFunctionActions.BulkCreateUIDataUpdateFunction>(
UIDataUpdateFunctionActions.ActionTypes.BulkCreateUIDataUpdateFunction
),
mergeMap((action) => {
const params = {
body: action.payload.uiDataUpdateFunctions
};
return this.UIDataUpdateFunctionApi.bulkCreate(params).pipe(
mergeMap((uiDataUpdateFunctions: UiDataUpdateFunction) => {
console.log(uiDataUpdateFunctions)
this code's console log objects in array.
I want it should be return as string array. When i tried define like this uiDataUpdateFunctions: UiDataUpdateFunction[] its give a an error (The independent variable of type 'OperatorFunction<UiDataUpdateFunction[], Action>' cannot be assigned to a parameter of type 'OperatorFunction<UiDataUpdateFunction, Action>'. The type 'UiDataUpdateFunction[]' is missing the following properties of type 'UiDataUpdateFunction': id, projectId, uiDataStoreId.). So i tried do it like this
mergeMap((uiDataUpdateFunctions: UiDataUpdateFunction[]= [{
id: '',
projectId: '',
uiDataStoreId: '',
}])
but its still give same error.I also tried doing .map() to convert to array on uiDataUpdateFunctions. Probally i can't write correctly. Shortly i want to return objects coming from the interface as a string array. What should i do for this ?

What is this structure in javascript return({object}={})=>{more code}?

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
}
}
}
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 and subject keys from it (undefined if not present) and tenure key (false if missing).
Performs some action with these args (checks error and returns object with 3 anonymous functions like getters)
It's a anonymous function
this
(object)=>{more code}
is equivalent to this
function functionName(object){
moreCode
}
your code example is a function called buildMakeTeacher which is returning an anonymous function which returns an object
Read about closure and curry a bit it will give you a better perspective.
But basically that means this function returns a new function which returns an object with callable actions.
So to call it you should do something like
buildMakeTeacher(someValidstor)({name: “foo”, subject: “bar”}).getSubject()

setting function's parameter as null

please doee anyone have an idea how the first code works and the second doesn't? i saw the first code somewhere and i have been trying to understand the idea behind it. thanks
const loadable = (importFunc, { fallback = null } = { fallback: null }) => {
const LazyComponent = lazy(importFunc);
return props => (
<Suspense fallback={fallback}>
<LazyComponent {...props} />
</Suspense>
);
};
When you destructure in the argument list with an object, an identifier after a colon indicates the new variable to put the property into.
This:
const test2 = ({ fallback: foo }) => {
// rest of function
means
const test2 = (parameter) => {
let foo = parameter.fallback;
// rest of function
But you're not using foo, but null - which the interpreter (and specification) recognizes as almost certainly being an accidental error. You don't want to put a value into an identifier named null, so it prohibits you from doing so.
Neither of the codes you provided are valid syntax for this reason.
If you just want to put the fallback property of the argument into a variable, omit the colon.
const test2 = ({ fallback }) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
If you also want to provide a default value in case the property is undefined, use = (not :).
const test2 = ({ fallback = null }) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
test2({});
If you also want to provide a default value for the whole object argument in case no arguments are passed, use another = after the argument is listed (very similar to what you're doing originally, but, again, with =, not :)
const test2 = ({ fallback = null } = {}) => {
console.log(fallback);
}
//calling
test2({fallback: "hello"});
test2({});
test2();

How does error value get assigned in React's AJAX and API example?

In React Docs - AJAX and APIs there is an example where a JSON object is created with a key that has no value.
I believe I am missing some fundamental understanding of JavaScript objects. What value is given to the error key in the following snippet and how does this value get there?
(error) => {
this.setState({
isLoaded: true,
error
})
}
Later, when the state is rendered, the value of error is assumed to have some message property. I have run the example code and it clearly works, but I am stuck trying to explain to another person how it works exactly.
if(error) {
return <div>Error: {error.message}</div>
It's object property shorthand ,
basically if you have a variable with the same name as the key, you can do :
const key = "someValue";
const obj = { key };
// instead of
const obj = { key : key };
const name = "John";
const age = 30;
const obj = {
name,
age
}
console.log(obj);
In the example you provided, error is an object having message inside it, something like :
const error = {
message: "some message",
// ...
}

add a property to a created object (Firebase Functions)

I'm hooking to the creation of objects on a specific collection (orders)
I need to add a new property to the object before it's saved, not returning anything, to no avail.
I have looked at the documentation at https://firebase.google.com/docs/reference/functions/functions.firestore.DocumentBuilder#writing_data
but it's for onUpdate so it doesn't work as i intend it.
exports.createOrder = firestore.document('orders/{orderId}').onCreate((snap, context) => {
const newOrder = snap.data()
console.log('triggered', newOrder)
const orderId = randomize('A0', 10)
console.log({ orderId })
return newOrder.ref.set({ orderId }, { merge: true })
//newOrder.ref.set is undefined
return newOrder.set({ orderId }, { merge: true })
//newOrder.set is undefined
})
snap.data() returns a raw JavaScript object whose properties contain the values of the fields in the document. It does not contain a property called ref (unless you had a document field also called ref).
If you need to write back to the document that changed, use the DocumentReference type object provided in snap.ref. See also the API documentation for the DocumentSnapshot type object passed to the function.
snap.ref.set(...)

Categories

Resources