How to set a default value - javascript

Here is how I extend the Immutable.Record
import Immutable from 'immutable';
const DATA_DEFAULTS = {
id: String,
data: String,
ref_id: String,
};
export default class Data
extends Immutable.Record(DATA_DEFAULTS) {}
If the json representation does not contain ref_id, then when I try to print the value of the field in the console of Chrome devtool, I will get:
> data.ref_id
String() { [native code] }
I think it is the reason why I cannot filter out entities with empty ref_id in a list
a = [] // a list of data
b = a.filter(x => x.ref_id != '') // b is the same as a
I suppose it can be fixed by either:
set a default value to a field in the Immutable.Record instance when the field is missing in the json data
use another way to detect if the field is not set in the instance
For the second approach, I have tried, for example, data.has('ref_id') and it always report true regardless if the field has any valid value.
My questions:
1) Can I set a default value in a Immutable.Record?
2) How to filter on field that may or may not exist in the Immutable.Record
3) What is the right way to test the existence of valid value in a field in an instance of Immutable.Record?

You are explicitly setting the default values of each of the fields to the function String. String is not a data type here, if that's what you thought. What you seem to want is
const DATA_DEFAULTS = {
id: '',
data: '',
ref_id: '',
};
1) Can I set a default value in a Immutable.Record?
Exactly how you already did, you just need to set the correct default value.
2) How to filter on field that may or may not exist in the Immutable.Record
Fields on a record always exist. From the docs:
Records always have a value for the keys they define. removeing a key from a record simply resets it to the default value for that key.
3) What is the right way to test the existence of valid value in a field in an instance of Immutable.Record?
You can use a default value that you know would not be explicitly assigned to the field otherwise. That could be null or a symbol.

Related

Remove undefined elements from a typescript class

I have created a javascript class so it can be reused in the project.
However, not all attributes are being set in the class at a given time.
For example, this is the interface of the address class
interface Address {
use: Code,
type: Code,
text: string,
city: string,
district: string,
state: string,
postalCode: string,
country: string,
period: Period,
value?: string | null,
}
class Address {
constructor() {
}
}
If you see the interface, you see that use has a type of Code which is another type of a class which has method called get() which will return a value or an Object
The Address class has a getObject property which will create an object which can later be strigified by using JSON.strigify()
Here is how I'm going to set the values of an object created by this class,
const address = new Address()
address.city = "Brisbane"
address.country = "AUS"
address.line.push("400, gStreet")
address.postalCode = "4000"
address.state = "QLD"
address.use = new Code("work")
However, when i call address.getObject() this will trigger an error because the use is not set undefined and therefore can't call the method, get().
How can I solve this issue?
Do I have to use something like lodash to remove undefined elements within an object before calling getObject()?
Thank you in advance.
I can comment due to StackOverflow:
// so this is a comment
the typescript type system is structural meaning that u can use objects when needed and object ( class instance ) when needed
for example, if u want typescript to help u with types and validations use ( classes, types, and interfaces ) otherwise u can use a plain javascript object as #Aluan Haddad said
U can read more here ( not mine ) typescript type system
Good luck

How to declare a Typescript array that will always be empty?

I'm declaring a private default inside a module. The value is an empty array. It will always be empty, because it's kind of a fallback value. TS wants me to type the array, but it seems I shouldn't declare what kinds of value the array will hold, because this function is used by many callers, each of whom works with different kinds of data.
I've got something like this:
const DATA_FOR_ERROR_CASES = []
export default function unpackData( packedData: string|undefined ) {
if(packedData === undefined) {
// return a Node-style callback tuple
return [
new TypeError('missing packedData'),
DATA_FOR_ERROR_CASES.slice()
]
}
/*
Otherwise, do really complex stuff, which can generate an
array OR a hash, depending on the string content of packedData
*/
return [
undefined, // as in Node, error arg is undefined in success case
unpackedData
]
}
I use an empty array as my default return because experimentation suggests this will permit callers to optimistically destructure it regardless whether they're expecting a hash or a list in success cases. Like so:
// one caller knows it'll get a hash (if things don't break)
let [ error, { name, address } ] = unpackData(packedContact)
// another caller expects an actual list
let [ error, [ firstChoice, secondChoice, ...otherChoices ] ] = unpackData(packedPrefs)
If unpacking fails, the first element will be some helpful Error instance, and the second value will be DATA_FOR_ERROR_CASES.
In error cases, the second example fails if DATA_FOR_ERROR_CASES is a hash, because you can't use array-destructuring on a POJO. You can use both array- and property-destructuring on an array. I want callers to be able to optimistically destructure, rather than having to do this:
// this sucks because it's so awkward
let [ error, unpacked ] = unpackData(packedPrefs)
if(error) throw error // ... or bail in some other way, preventing next line
let [ firstChoice, secondChoice, ...otherChoices ] = unpacked
My question: how should I declare the type of DATA_FOR_ERROR_CASES?
TS won't accept this:
const DATA_FOR_ERROR_CASES: Array = []
// Generic type 'Array<T>' requires 1 type argument(s). ts(2314)

Override value in the form using yup when condition applies

I am trying to build a yup validation schema, but I couldn't figure out how to transform value to a default every time when it doesn't match the schema.
I was trying to check is value higher than 0 and not undefined, so then this form value would be required, otherwise I would like to set it to the empty string.
This is my code:
reason: string()
.when('value', {
is: val => Boolean(val),
then: string().required('This field is required'),
otherwise: string().transform((value) => value ? value : '')
})
Thanks a lot!

Sequelize.js setter function not working as I expect

I'm having trouble using the setter functions on my Sequelize js model properties.
What I want to do is when one property is given a value use that value to populate another property in the table at the same time.
In my model this is the code I have for the property in question...
date_time_paid: {
type:DataTypes.DATE,
set(val) {
const date = new Date(val);
this.setDataValue('date_time_paid', val); // set the the current property
this.setDataValue('month_paid', `${date.getFullYear()}-${(date.getMonth() + 1)}`); //also set another property on the same row
},
},
What I expect to happen is for the date_time_paid column to store the raw value and the month_paid column to store a string derived from it. But when I run my seeder to populate the table with test data the value for the month_paid column remains null.
Is this the correct use of a setter function?
If it is what have I done wrong that means it's not working?
I think you need a just a getter. Forget about date_time_paid and make getter for month_paid:
get month_paid(){
const date = new Date(this.date_time_paid);
return `${date.getFullYear()}-${(date.getMonth() + 1)}`;
}

Dojo lang.replace - how to provide default value, instead of 'undefined'?

Dojo lang.replace() replaces the undefined placeholders with undefined text. Is it possible to define the default value within placeholder?
Let's say I want to have the following placeholder:
<div class="message">The query returned {result.rows:0} rows</div>
The placeholder will be replaced with the numbers of rows returned, but when the variable rows is not available (for exapmle, the result contains error message) it will be replaced with 0.
There are two approaches you can consider. The first is to mixin the results object with defaults before passing it into the replace function.
var defaults = {
rows: 0
};
var data = lang.mixin(lang.clone(defaults), result);
lang.replace(template, data);
The second approach is instead of passing a data object, pass a function that knows how to default the value when missing.
http://dojotoolkit.org/reference-guide/1.9/dojo/_base/lang.html#with-a-function

Categories

Resources