All posts by admin

Setting up Java Env and Android emulator on Mac env

  • https://blog.logrocket.com/run-react-native-apps-android-emulator-macos/
  • https://javarepos.com/lib/jenv-jenv-java-general-utility-functions


brew install jenv

Updating Homebrew…
==> Downloading https://ghcr.io/v2/homebrew/portable-ruby/portable-ruby/blobs/sha256:0cb1cc7af109437fe0e020c9f3b7b95c3c709b140bde9f991ad2c1433496dd42
######################################################################### 100.0%
==> Pouring portable-ruby-2.6.8.yosemite.bottle.tar.gz
==> Auto-updated Homebrew!

After the command completes, we must tell our system where to look so it can use jenv, so we need to add it to our path. To do this, we must run the following command in our terminal:


echo ‘export PATH=”$HOME/.jenv/bin:$PATH”‘ >> ~/.zshrc
echo ‘eval “$(jenv init -)”‘ >> ~/.zshrc

We want to install JDK8 because that’s the version that works with our Android SDK Manager. Type the following into the terminal:

brew install adoptopenjdk8

brew install homebrew/cask-versions/adoptopenjdk8

This will install the latest version of Java 8 to a special directory in macOS. Let’s see which directory that is:

ls -1 /Library/Java/JavaVirtualMachines

adoptopenjdk-8.jdk

jenv add /Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/

openjdk64-1.8.0.292 added
1.8.0.292 added
1.8 added

jenv versions
system
1.8
1.8.0.292
15
15.0
* 15.0.2 (set by /Users/ricky_tsao/.java-version)
openjdk64-1.8.0.292
openjdk64-15.0.2

jenv info java
Jenv will exec : /Users/ricky_tsao/.jenv/versions/15.0.2/bin/java
Exported variables :
JAVA_HOME=/Users/ricky_tsao/.jenv/versions/15.0.2

java –version
openjdk 15.0.2 2021-01-19
OpenJDK Runtime Environment (build 15.0.2+7-27)
OpenJDK 64-Bit Server VM (build 15.0.2+7-27, mixed mode, sharing)

jenv doctor
[OK] No JAVA_HOME set
[OK] Java binaries in path are jenv shims
[OK] Jenv is correctly loaded

Function Composition (functional programming)

ref – http://chineseruleof8.com/code/index.php/2019/01/03/functions-are-first-class-objects-js/

function vs procedure

Procedure – collection of functionalities.
May or may not have input, or return values, and have multiple tasks.

Functions – Mathematical functions.

  • Have input
  • Return value
  • Simplified to a single task
  • Easy for reuse

Step 1

We first have a string literal.
We have a function called prepareString.

And by scope, it reference the str and trims it for str1.
Then str1 replaces it with regex for str2.
Finally str2 upper cases everything for str3.
str3 then splits into an array.

Finally we loop through this array and try to find A, AN, or THE. If its found, delete it using splice.

Step 2 – separate them into one task functions

becomes

becomes

becomes

becomes

becomes

Using noArticles:

becomes

Step 3

Then we need to change these functions into arrow functions.

Step 4 – Optionally call them together

pipe

The pipe function goes through each function and applies the accumulator string to each function..starting with the initiator x.

So if x is ‘word’, and the first function is !${param}, this will return ‘!word’.
Then the 2nd function is *${param}, then we’d get ‘*!word’.

Basically, it would apply the result of the current function to the param of the next function.

Notice our spread operators in the parameter. Its taking all the params together and bringing them together as the array fns.

Our output would be:

$word
!$word
(!$word)
*(!$word)
*(!$word)–>
<--*(!$word)-->

We can also start from the right function, (by using reduceRight) so now our output would like this:

<--word <--word-->
*<--word-->
(*<--word-->)
!(*<--word-->)
$!(*<--word-->)

Now, going back to our work, we would stick each function to process on the string. Then use the returned string as the input for the next function. Literally, the functions put together act as a pipe for strings to go through and be processed.

Function Composition 2

Given…

and situation is:

1) Convert each statement to a function that can accept and act on any array.

2) Compose a function that will remove both zero or lower scores and scores over 100. Test it using the scores array.

3) Compose a function that will do all the modifications to an array. Test it using the scores array.

4) Create a function that will accept an array and return the average. Use the function that sums scores and the function that counts scores or the length property.

5) Compose a function that will do all the modifications on an array and return an average.

Arity

So we still have our pipe function. Remember that it takes in an array of functions, and an initial string x. (Henry)

It goes through the first function and gives ‘Henry’ as the first parameter. The return value of the 1st function (user object) is then inserted into the 2nd function.

The return value of the 2nd function is then inserted into the 3rd function, so on and so forth.

users array is the data that will be bind to getUsers function.

As you can see we a function like so:

We need to change it using bind so that we can pass in users as the data, and we get a reference to it all. That way, users is matched up to param arr.

We get partGetUser, and then when we execute it inside pipe, we can pass in ‘Henry’ to param name of getUser.

storeUser is just a standard function.

we have our cloneObj that takes an object and clones it using JSON. We leave it as is.

Then we have updateScore:

we need to change it like this:

updateTries is used as is.

We put updateUser, cloneObj, partUpdateScore30, and updateTries into our pipe utility function.
We get the result back when ‘Henry’ is inserted into the beginning of the pipe.

Arity full code

functional programming

Building software by creating pure functions, avoid shared state, mutable data, and side-effects.

application state flows through pure functions.

Side Effects and Pure Functions

Notice the data is the array of users.
We have our mutable function that literally uses scope to access users and change its contents.

For the pure functions we take in parameters, and we do not modify these inputs. Instead, we return new arrays with shallow copied data. Notice we never touch param arr, nor name. We simply get the data we need, and return new arrays.

We then use the pure functions to calculate new scores.
Then give it to our mutable functions to update our data.

Avoid Shared State

Javascript stores data in objects and variables. This is called state.

Notice how users are shared via closure scope. We need to void this by passing state (users)
from one function to another.

Mutation

how to avoid mutating? Clone it

but…for objects with nested data:

we need to convert it to string, then parse it back into an object.

We can do the same with arrays:

Object.assign and spread operator works the same way.

For Arrays, spreading a null would give an error

For Objects, both silently exclude the null value with no error.

Pure Functions

Pure vs Impure (procedures)

Functional programming almost always use pure functions.
Creates and returns value based on input parameters and causes no side effects

1) Changing value globally
2) Changing value of input
3) Throwing exception
4) Logging or printing to screen, writing to file, change to db.
5) Invoking other functions that have side-effects

Higher Order Function

Higher Order Function – function that takes function as input parameter or returns a function.

map is higher order because it takes function as input.

other functions that returns functions are higher order.

Reduce (javascript)

Reduce sums up all the items in the array where the first parameter is the callback and second param is the starting value.

Let’s group grades into an object:

When to use useMemo, useEffect, and useCallback

ref – https://www.geeksforgeeks.org/when-to-use-usecallback-usememo-and-useeffect/

useCallback

useCallBack demo

Let’s see this in the following code, doubleFactory creates and returns a function:

doube1 and double2 doubles the value passed to them and are created by the same factory function. The two functions even when they share the same code, are not equal, here (double1 === double2) evaluates to false.

When to use useCallback: In React, a component usually has some callback function created within it.

handleChange function objects are different on every rendering of MyComponent. And there are several cases when we may want the same function object between multiple renderings.

In our example, we have getItems which is executed whenever we enter some digits.
We pass this inside a child component List to be rendered.

So her’es how it works. Our input is being changed inside input element. Since the state changes, our variables (such as getItems) will also change and get re-calculated.

And since getItems is passed into List component, it will see that if getItems has changed, then it needs to re-render.

App.js

In our List, we look at getItems array. If it changes, we update and set our items to this new getItems.

List

So

1) parent input state changes from Input Element
2) state change makes everything re-calculate, including getItems.
3) Since getItems is passed into child component, child sees getItems has changed, and thus, will re-render via useEffect.

The following will be the output when a user enters a number into the input field.

It can be seen from the console log that when the app is rendered for the first time, items are fetched, and “fetching items” are printed. Now if we input some different numbers, we see that items are fetched once again. This is the expected result.

Now the weird thing is,
when we press the button to change the theme,

we see that the getItems is still being called…even when the input field is not modified!

The reason behind this behavior is that when we press the button,

the app component is rerendered

and hence the function getItems() inside App is again created and we know that two objects are referentially different and thus re-rendered.

But why does the the button press trigger the component to re-reproduce getItem() again?

Because useState causes a re-render on the call to the setState method. It does not have any dependencies like useMemo or useEffect. This is why our component re-renders.

This is why getItem get called again even though the input field is not modified.

Thus, useEffect hook calls the setItems and prints “Fetching items” as its dependency has changed.

The solution to the above problem:

Here we can use the useCallback function to memoise the getItems() function depending upon the input number.

We don’t want to recreate the function unless the input changes, and hence, on pressing the button (changing the theme) items will not be fetched.

Now we use the useCallback hook to memoize the getitems function which takes the function and a dependency list. The dependency list in our case includes only the input.

useMemo

There are two cases where using useMemo can be helpful:

Case 1

When a component uses a value computed using a time-consuming function.

Here the slow function is called every time MyComponent is rendered, maybe because some stateful variable is changed or some other component caused the rerendering.

Solution: By memoizing the returned value of the slow function using the useMemo hook we can save ourselves from the delay it may cause.

here we use the useMemo hook to cache the returned value and the dependency list contains the data stateful variable. Now every time the component is rendered, if the data variable is not altered, we get the memoized value without calling the CPU intensive function. Hence, it improves the performance.

Case 2

Now consider another scenario when we have a component that does something when some data changes, for example, a let’s take the hook useEffect which logs if some dependency changes.

In the above code, every time the component is rendered, “Hello world” is printed on the console due to the fact that the data object that is stored in the previous render is referentially different in the next render and hence the useEffect hook runs the console.log function. In real-world useEffect can contain some functionality that we don’t want to be repeated if its dependencies do not change.

Solution: We can memoize the data object using the useMemo hook so that rendering of the component won’t create a new data object and hence useEffect will not call its body.

Now when the component renders for the second time and if the number stateful variable is not modified then console.log() is not executed.

useEffect

useEffect: In react, side effects of some state changes are not allowed in functional components. useEffect is always called after the render phase of the component. This is to avoid any side-effects from happening during the render commit phase (as it’d cause the component to become highly inconsistent and keep trying to render itself). This hook takes a function to be executed and a list of dependencies, changing which will cause the execution of the hook’s body.

To understand its proper use. let’s see a simple example:

Example: Consider a scenario where we have to fetch some data from some API once the components are mounted. In the example code, we simulate the server with our data object with values of different colours and fruits. We want to print the list of items depending on the button being pressed. Hence we have two state variables currentChoice and items which are modified by pressing the buttons. When a button is pressed it changes the currentChoice and the body of useEffect is called and current choice’s items are printed using a map. Now if we don’t use useEffect, every time a button is pressed data will be fetched from the server even if the choice does not change. In such a condition this hook helps us to not call the fetching logic unless our choice changes.

When the application loads for the first time, data is fetched from our fake server. This can be seen in the console in the image below. And when we press the Fruits button, appropriate data is again fetched from the server and we can see that “Data is fetched” is again printed in the console. But if we press the Fruits button again, we don’t have to get the data from the server again as our choice state does not change.

Hence, a useCallback hook should be used when we want to memoize a callback,

and to memoize the result of a function to avoid expensive computation we can use useMemo.

useEffect is used to produce side effects to some state changes.

usMemo vs useCallback

useMemo recalculates a value if the elements in its dependency array change (if there are no dependencies – i.e. the array is empty, it will recalculate only once). If the array is left out, it will recalculate on every render…just like useEffect. The difference herein lies in that it runs during the render of the component and not before.

useEffect is called after each render when a certain state has changed in the dependency array, or is left out altogether. If the array is empty, it will only be run once on the initial mount (and unmount if you return a cleanup function).