ES6 Spread/Rest Operator

ES6 has a handy feature called the Spread/Rest operator notated as .... The reason is has two names is because based on the use, it can do two different things.

Spread

For example, we can spread an array of values into a function parameters.

function myFunction(a, b, c) {
   console.log(a, b, c)
}

myFunction(...[1, 2, 3]) // outputs 1, 2, 3

We can aslo spread one array into another to improve array concatenation like so:

const a = [1, 2];
const b = [3, 4]'
const c = [...a, ...b];

console.log(c); // Results in [1, 2, 3, 4]

Rest

You can also use the operator to gather items into an array. A common usage of this is accepting extra arguments into a function

function myFunction(one, ...args) {
    console.log(args);
}

myFunction(1, 2, 3); // prints 1, [2, 3]

For more info, check the MDN docs

Making your Smart Contracts Ownable

A good practice during Dapp development is to make your contracts ownable. This will allow you to add modifiers to prevent certain functions form being used. Be careful though, because this can remove the ‘decentralized’ aspects of the contract.

pragma solidity ^0.4.23;

contract Ownable {
  address public owner;

  constructor() public {
    owner = msg.sender;
  }

  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
}

contract Example is Ownable {
  function exampleFunction() public view onlyOwner {
    // code here
  }
}

Now you only the account whoe deployed this contract can call exampleFunction. To see a better example and many more examples, check out OpenZepplin.

Removing Your Smart Contract from a Testnet with Solidity’s Self Destruct

When developing Dapps, you will eventually need to deploy your app the a testnet like Rospen. When doing this, you have an option to self destruct – something you can’t do on the main net. This is helpful to keep the test net clean. Here is how we would implement this.

pragma solidity ^0.4.23;

contract Mortal {
    address owner;

    function Mortal() public {
      owner = msg.sender;
    }

    function kill() public {
      if (msg.sender == owner) selfdestruct(owner);
    }
}


contract Example is Mortal {
}

And that’s it! now you can call kill on your Example contract to remove it from the testnet.

Array Slice in Javascript

Something I need to do freqeuntly in Javascript (and most programming languages) is get a sub array from a larger array. Javascript provides the handy Array.slice method for this. Here is a quick snippet on how to use it.

const arrray = [1, 2, 3, 4];
const subarray = arrray.slice(1, 3);

console.log(subarray) // prints 2, 3, 4

Great Resource for Learning Regex in Javascript

Regex is a powerful way to searching in most every programming language. Althought when someone new to regex views one, they can become intimidated quickly. I’ll admit some regex strings are daunting, but with practice, this ambiguity clears (mostly :P).

Here are some create resoruces for learning Regex.

flaviocopes – This site has a great walkthrough, and slowly builds up to some more difficult Regex.

Learn Regex the Easy Way – A great tutorial that is language agnostic, but is a great from beginning to advance.

Learn Regular Expressions for Beginners – Back to the Javascript tutorials with this great one.

https://regex101.com/ – This isn’t a tutorial, but is a great way to test out your Regex

 

Android Support Material Button

In version 28.0.0 (currently in alpha) Android added a Material Button. Here is a quick snippet.

<com.google.android.material.button.MaterialButton
    android:id="@+id/material_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/button_label_enabled">

This code makes it pretty easy to get a pretty button that is backwards compatabile. Check out the full list of attributes and some more examples in the references below.

Using ListAdapter with RecyclerView

Android added the ListAdpater in the 27.1.0 Support Library Update which allows for much more performant updating of list items. This library uses the DiffUtil to better calculate changes. Let’s start with some examples.

Getting Setup

First, I recommend starting a new project following the Android guide: https://developer.android.com/guide/topics/ui/layout/recyclerview. Get that set up and we can show the improvement.

Notice, for the previous set up you would have to do the following to change items in your adapter.

fun changeItem(items: String) {
  myDataset = items;
  notifyDataSetChanged()
}

Of you could use the following for inserting to save on performance.

fun addItem(item: String) {
  myDataset.add(item)
  notifyItemInserted(myDataset.size)
}

But what about editing and deleting? That is where the new ListAdpater comes in.

Using the List Adapter

So, first we will create a StringDiffCallback which will extend DiffUtil.ItemCallback. This allows us to creat a custom comparator for our items. In the real world, you would probably have a model that you need to check for difference rather than strings.

class StringDiffCallback : DiffUtil.ItemCallback() {
    override fun areItemsTheSame(oldItem: String?, newItem: String?): Boolean {
        return oldItem == newItem
    }

    override fun areContentsTheSame(oldItem: String?, newItem: String?): Boolean {
        return oldItem == newItem
    }
}

Then, we need to create a new adapter (or update the other one) to extend ListAdapter. We pass this new adapter an instance of our StringDiffCallback to use. Also, we’ve update to allow for the activity to pass a clickListner (for update the items).

class NewAdapter(private val clickListener: (String) -> Unit) :
        ListAdapter(StringDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val inflater = LayoutInflater.from(parent.context)
        return ViewHolder(inflater.inflate(R.layout.my_text_view, parent, false))
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position), clickListener)
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(item: String, clickListener: (String) -> Unit) {
            itemView.setOnClickListener { clickListener(item) }
        }
    }
}

Back in our activity we have the following to set up the NewAdapter.

override fun onCreate(savedInstanceState: Bundle?) {
      super.onCreate(savedInstanceState)
      setContentView(R.layout.activity_main)

      val myDataset: List = listOf("a", "b", "c")

      viewManager = LinearLayoutManager(this)

      newAdapter = NewAdapter(fun (item: String) {
          // Do some operations on dataset
          newAdapter.submitList(myDataset)
      })
      newAdapter.submitList(myDataset)

      recyclerView = findViewById(R.id.my_recycler_view).apply {
          setHasFixedSize(true)
          layoutManager = viewManager
          adapter = newAdapter
      }
}

The main item to note is the following where we can resubmit our list using the ListAdapter‘s submitList function. That function will use the diff util we passed and update our items accordingly and in a performant way.

newAdapter = NewAdapter(fun (item: String) {
   // Do some operations on dataset
   newAdapter.submitList(myDataset)
}

Check if MetaMask is Locked

If you are building a DApp and need to create a display to let users know the status of MetaMask, here is some quick code to get you started


function checkMetaMask() {
  // Metamask is not installed
  if (typeof web3 === 'undefined') {
   this.notInstalled = true;
   return;
  }
  
  // Metamask is locked
  const account = web3.eth.accounts[0];
  if (!account) { 
   // locked
  }
},

Per the offical docs, it looks like you should set an interval to keep checking: https://github.com/MetaMask/faq/blob/master/DEVELOPERS.md#ear-listening-for-selected-account-changes

And that’s it!

Static Class in Kotlin

Earlier this week I need to create a static class in Kotlin. If you are coming from Java like myself, the syntax is slightly different, but still easy. Here’s the code

class Constants { 
  companion object {
    val constantKey = "KeyValue"    
    fun getConstant() : String { return "KeyValueFromFun" }
  } 
}

You can then use the class like this:

Constants.constantKey
Constants.getConstant()