Posted onEdited onInjavascript Symbols count in article: 288Reading time ≈1 mins.
Optional chaining
Why optional chaining
Have you write the following code before?
1 2 3
if (user && user.address && user.address.street) { console.log(user.address.street); }
With optional chaining operator, you don’t need so many && to get a deeply nested property.
1
console.log(user?.address?.street);
How to use optional chaining
The optional chaining (?.) operator accesses an object’s property or calls a function. If the object accessed or function called using this operator is undefined or null, the expression short circuits and evaluates to undefined instead of throwing an error.
Access object’s property
1 2 3 4 5 6
const person = { name: 'Philip', };
console.log(person.info.address); // TypeError: Cannot read property 'address' of undefined.(Because, person does not have property 'info') console.log(person.info?.address); // undefined
Call a function
1 2 3 4 5 6 7 8 9 10
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { // Testing if onError really exists if (onError) { onError(err.message); } } }
With optional chaining, you don’t need too check weather onError is defined or not.
1 2 3 4 5 6 7
functiondoSomething(onContent, onError) { try { // Do something with the data } catch (err) { onError?.(err.message); // No exception if onError is undefined } }
Short circuit
When using optional chaining, if the left operand is null or undefined, the expression will not be evaluated, for instance:
1 2 3 4 5
let i = 0; const nums = null; const firstNumber = nums?.[i++]; console.log(x); // 0, since num?. trigger short circuit, [i++] is not evaluated.
?. not work for non-declared root object
Optional chaining can not be used with a non-declared root object, but can be used with a root object that is null or undefined.
1 2 3
console.log(a?.b); // Uncaught ReferenceError: a is not defined console.log(null?.b); // undefined console.log(undefined?.b); // undefined
In javascript, not defined and undefined are two different concepts. See undefined vs not defined
Posted onEdited onInjavascript Symbols count in article: 121Reading time ≈1 mins.
undefined vs not defined
In JavaScript, undefined and not defined are two different concepts.
undefined: a variable has been declared but has not yet been assigned a value.
not defined: a variable has not been declared(not exists).
undefined
1 2
let a; console.log(a); // undefined
not defined
1
console.log(b); // Uncaught ReferenceError: b is not defined
Whenever you try to access a variable that is not declared, JavaScript throws an error: Uncaught ReferenceError: xxx is not defined. This is because variable b is not declared anywhere in the code. but you can still use typeof to check if a variable is defined or not.
typeof
1 2 3
let a; console.log(typeof a); // undefined console.log(typeof b); // undefined, even b is not defined
Limitation: The fakeAsync() function won’t work if the test body makes an XMLHttpRequest (XHR) call. XHR calls within a test are rare, but if you need to call XHR, see the waitForAsync() section.
it('should show quote after getQuote (waitForAsync)', waitForAsync(() => { fixture.detectChanges(); // ngOnInit() expect(quoteEl.textContent).withContext('should show placeholder').toBe('...');
fixture.whenStable().then(() => { // wait for async getQuote fixture.detectChanges(); // update view with quote expect(quoteEl.textContent).toBe(testQuote); expect(errorMessage()).withContext('should not show error').toBeNull(); }); }));
// This object is the return value of init will be assigned to instance. return { // Public methods and variables publicVariable: 'I am public variable', publicMethod: () => { console.log('Public method'); }, }; };
// Public method to get the singleton instance constgetInstance = () => { if (!instance) { instance = init(); } return instance; };
// Expose the public method return { getInstance, }; })();
functioncreateInstance(name) { if (!instance) { // Init code goes here, If you want to exact init to a function, you must use createInstance.prototype.init = function(name){this.name = name}. This will make init public to every instance, it's bad idea! this.name = name; instance = this; }
return instance; }
return createInstance; })();
const a = newSingleton('zdd'); const b = newSingleton('ddz'); console.log(a === b); // true
下面是使用ES6的class来实现单例模式。代码更加简洁优雅。
Use class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
classSingleton { constructor() { if (!Singleton.instance) { Singleton.instance = this; // Your initialization code here } returnSingleton.instance; }
// Additional properties and methods can be added here }
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
# Step 3: Add the stories to the Confluence page for story in jira_stories: story_title = story["fields"]["summary"] story_description = story["fields"]["description"]
for issue in issue_list: if issue['priority'] in priority_mapping: issue['priority'] = priority_mapping[issue['priority']] if issue['status'] in status_mapping: issue['status'] = status_mapping[issue['status']] new_issue_list.append(issue) return new_issue_list
# set color for header for rows in sheet.iter_rows(min_row=1, max_row=1): for cell in rows: cell.fill = PatternFill(fgColor="002060", fill_type="solid") cell.font = Font(color="FFFFFF")
for issue in issue_list: sheet.append(list(issue.values())) # fill in color my_red = Color(rgb='00B050') my_fill = PatternFill(patternType='solid', fgColor=my_red) for row_cells in sheet.iter_rows(min_row=1, max_row=sheet.max_row): if row_cells[3].value == 'Done': row_cells[3].fill = my_fill
If there is no affected apps, nx print-affected will show the following output. look at the projects property, its empty, which means there is no affected apps.
If your apps/libs was created manually, you have to make sure that there is a file project.json under the root of your app/lib, and have the following content at least.
Posted onEdited onInandroid Symbols count in article: 611Reading time ≈2 mins.
Android Studio Tips -1
1. Wireless debugging with Android device
Select Pair Devices using Wi-Fi under emulator dropdown list.
Enable debug mode on your android device(see here for more details).
On your android device, select Settings | Developer options | Wireless debugging | Pair using QR code to enable wireless debugging.
2. Fix Manifest merged errors
Open AndroidManifest.xml file.
Click Merged Manifest tab at the bottom of the editor.
Scroll down to the bottom to see the errors.
3. View database file in Android Studio
Select View | Tools Window | App Inspection from the main menu.
Launch your app on a device/Emulator running API level 26 or higher.
If you see a red close icon on your database file which means your database was not opened, you can operate on your app to open the database(such as click a button, open a fragment or whatever action which can open the database).
If you database was opened, you can click the table under this database to view the data.
4. Filter logs in Logcat
Select Logcat at the bottom of Android Studio.
Select the emulator/device where your app runs on.
Focus the filter input box, and press Ctrl + Space to open the filter dialog. then select the filter options you want.
For example, if you want to see only error logs for package com.jiyuzhai.kaishuzidian, you can input package: com.jiyuzhai.kaishuzidian level: error as a filter.
5. Open xml layout file in split mode
Do you ever encounter this situation? whenever you open an xml layout file, it opens in design mode by default. You can do the following to open it in split mode by default.
Open Settings | Editor | Design Tools from the main menu.
Check Prefer XML editor option.
Click OK button.
File xxx already exists, it cannot be overwritten by SerializableChange(file=xxx, fileStatus=NEW, normalizedPath=xxx.class).
In Android menu, select Build | Clean Project, then rebuild, that’s it!
Android emulator stop working.
Delete the lock file under avd folder, here is the lock file path under android sdk folder.