5 Minute JavaScript #18: reduce

The past weeks we dived in the wonderful world of array methods. Previously we already discussed forEach, filter, some and every, and map. Today we’ll take a look at the reduce method. While being extremely useful, its concept can be hard to grasp.

Also known as fold (in this case foldLeft) in other functional programming languages, reduce kan be used to combine all elements of an array into one single return value. That return value can be anything. It could be an array (then the reduce functions as a filter/map), but it can also be: an object, string, number, boolean… Everything is possible.

A simple example can be to use the reduce method for calculating a sum. Here’s the code how we would write it in any other imperative language.

var numbers = [1, 2, 3];
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
	sum += numbers[i];
}

We can rewrite this code as follows using the reduce method

var sum = numbers.reduce(function (prev, cur) { return prev + cur; });

The reduce callback function takes two important parameters (prev, cur in this case). First of all we have the previous value. This is the value that got returned in the previous callback function. The current parameter is the current item in the list.

You might get your head around this functionality, but it’s not really useful in real applications. Its real strength lies in the fact that you can press a lot of elements together into one single return value. A use case for reduce might be this:

var user = { id: 'UUID', version: 0 };
var users = [/* list of users */];
var idVersionMap = users.reduce(function (map, user){ 
    map[user.id] = user.version; 
    return map; 
}, {});

In our blogpost about the map method we used map to create a new list of objects (with id and version). Here, we use the reduce method to create a single object that acts as a map with key = id and value = version. The empty {} that we passed along in the reduce callback function is the initial value the method needs to use.

Introduction to Oracle Database 12c

With the launch of DB 12c in 2013, Oracle introduced a new architectural concept, called “multitenant databases”, where you have one super database (=container; CDB) and one or more sub databases (= pluggable DBs; PDB).

Before running the installer on an Oracle Linux 6 environment, a library can be installed through yum to meet all the system per-requisites:

yum install oracle-rdbms-server-12cR1-preinstall

The software installer and DBCA are similar to 11g, except for this screen where you can pre-configure your CDB and PDBs:

db12c01

This DBCA execution will not only create a CDB and 1 PDB, but a “seed pluggable database” as well.  You can use this seed database as a template to create other pluggable databases.

db12c02

By default, after running the DBCA, all CDBs and PDBs are up and running.

Now, we will reboot the host machine and try to start all of our components.

Is there a difference when starting the listener and the CDB?

No!  You can start the listener and your CDB in exactly the same way as you did with your pre-12c database.

How can you connect to the CDB?

Very simple: just the same as in the past with pre-12c databases.

$ sqlplus system@apexdev

SQL*Plus: Release 12.1.0.1.0 Production on Thu Mar 19 22:53:55 2015

Copyright (c) 1982, 2013, Oracle.  All rights reserved.

Enter password:

Last Successful login time: Mon Mar 16 2015 22:20:50 +01:00

Connected to:

Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 – 64bit Production

With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL>

Are the PDBs opened by default, when starting the CDB?

No.  This can be verified by this query:

SQL> select open_mode from v$pdbs where name=’APEXDEV_PDB1′;

OPEN_MODE
———-
MOUNTED

The PDB is mounted; to open it, just run this command:

SQL> alter pluggable database apexdev_pdb1 open read write;

Pluggable database altered.

SQL> select open_mode from v$pdbs where name=’APEXDEV_PDB1′;

OPEN_MODE
———-
READ WRITE

Note: this must be done as “SYSDBA”.

How can we connect to the PDB?

There are 2 methods:

First method: connect to the CDB and then switch to the PDB by setting the container:

$ sqlplus system@apexdev

SQL> show con_name

CON_NAME
——————————
CDB$ROOT
SQL> alter session set container=apexdev_pdb1;

Session altered.

SQL> show con_name

CON_NAME
——————————
APEXDEV_PDB1

Second method: Modify your tnsnames.ora file by adding an entry for the PDB, based on the CDB entry.

Now, you can connect as usual to the PDB:

[oracle@ol6db1 oracle]$ sqlplus system@apexdev_pdb1

SQL*Plus: Release 12.1.0.1.0 Production on Tue Mar 24 20:37:38 2015

Copyright (c) 1982, 2013, Oracle. All rights reserved.

Enter password:
Last Successful login time: Thu Mar 19 2015 18:59:51 +01:00

Connected to:
Oracle Database 12c Enterprise Edition Release 12.1.0.1.0 – 64bit Production
With the Partitioning, OLAP, Advanced Analytics and Real Application Testing options

SQL> show con_name

CON_NAME
——————————
APEXDEV_PDB1

As you can see, it is all quite easy.  One of the main benefits of this architecture is that you can handle every PDB as a separate database that can be upgraded or plugged/unplugged independently from other databases.

And of course your database will be ready for the cloud!

5 Minute JavaScript #17: some and every

In the previous blogpost we discussed the map method on arrays in JavaScript. We still have some useful methods the go. Next in line are the some and every methods. These methods are similar and can be very useful when validating data.

var isEven = function (n) { return n % 2 === 0 };
var areAllEven = [2, 4, 6].every(isEven);
var someEven = [1, 2, 3].some(isEven);

The every method will check if for every element in the list, the callback functions returns true. If there is one single item in the array that returns false, the every method will return false as well. The some method is satisfied when there is at least one element in the array where the callback returns true.

var stockItem = { hasBeenShipped: true };
var selection = [/* list of stock items selected in a list */];
var hasNotBeenShipped = function (si) { return !si.hasBeenShipped };
var hasBeenShipped = function (si) { return si.hasBeenShipped };

$('#sendStockItems').attr('disabled', selection.every(hasNotBeenShipped));
$('#sendStockItems').attr('disabled', selection.some(hasBeenShipped));

The example here will disable a button when the selection in the list contains one or more items that already have been shipped. This code is very readable and concise. You can almost read exactly what it does: set attribute disabled when selection has some items that hasBeenShipped.

5 Minute JavaScript #16: map

Last week we took a look at the filter functionality. This week I will show you one of my favourite array methods called: “map”. It’s extremely powerful and useful in so many ways. The purpose of map is simple, it transforms an item in an array and pushes that transformation into a new array. The method then returns that newly created array with all the transformed items. A simple example will show you what it does.

var square = function (item) { return item * item; };
var squares = [1, 2, 3, 4].map(square);

In this example we just square a number in the array. The result will be a new array but with the squared items.

This example is easy to understand, but you might wonder what the practical use is for this function. Well in a lot of applications I find myself using map to select the identifier from an object and pass along a map of id’s.

var user = { id: 'UUID', version: 0, name: 'User 1' };
var users = [/* a list of users */];
var ids = users.map(function (u) {return u.id;}); 
var versions = users.map(function (u) {return u.version});
var idsAndVersions = users.map(function (u) { 
    return { 
        id: u.id, 
        version: u.version 
    };
});

These lists can be used in frameworks, api’s, ajax requests, caching, etc… everywhere you don’t need to know / send the full information of the user.

5 Things I wish I knew about APEX when I just started (part 3)

In my previous post of this series, I talked about cookie sharing in APEX. The next post in this series is about build options, I hope you enjoy it.

Build Options

Imagine having to release an apex application, but you don’t want some parts released in to the production environment yet, because they are unfinished, or not tested. Or you want to disable a module in your application for some reason.

Apex provides a solution for this called build options.

You can find the build options under shared components > logic > build options

Let’s create 2 build options:

The first one will keep the component active in our development environment, but will disable it on export so the developed content is disabled in our production environment.

buildoptions1

The second one will disable content in the application, and take over this behavior on export to our production environment.

buildoptions2

For the status there are two options possible:

Exclude, will disable the content in the current application, and include will keep it enabled in the current application.

For the default on export there are 3 possible combinations:

Same as current will take over whatever has been chosen in status when exporting a page. Exclude will disable the components on export of the application. Include will enable the components on export of the application.

Build options can be attached to any component in apex: pages, processes, regions, items, and can be found under the configuration tab when editing the components.

buildoptions3

As a test you can put the 2 build options on some page items in your current application.

When you run the page you will notice that in your development environment, one item will be visible and one will be gone from the page.

When you take an export and import it back in the new environment you will notice both items are removed from the page.

That’s it! The fourth blog in this series will be about recovering applications and page elements using flashback, and will be online soon.

5 Minute JavaScript #15: filter

In the previous blogpost we discussed the forEach method that iterates over every array. We can now create a filtered array by using this function.

var filtered = []
arr.forEach(function (item) { if (item.isOkay) filtered.push(item); });

While this will work fine, we still need to predefine our filtered array and push it in this array ourselves. We don’t need to… we could just use the filter method on the array prototype.

var filtered = arr.filter(function (item) { return item.isOkay; });

This code isn’t only more readable and a little shorter, it also allows you to chain these methods. Also, you can use abstract validation functions to reuse the filtering.

var isEven = function (number) { return number % 2 === 0; };
var filtered = [1, 2, 3].filter(isEven);

A more practical example:

var stockItem = { category: "toys" /*, and other properties */ };
var stockItems = [/* has a bunch of stockitems with different categories */];

var product = { category: "toys", stockItems: [] };
var products = [/* has a bunch of products */];

var belongsToToyCategory = function (item) { return item.category === "toys";  };

var filteredStockItems = stockItems.filter(belongsToToyCategory);
var filteredProducts = products.filter(belongsToToyCategory);

5 Minute JavaScript #14: forEach

After discussing how to create a range in the last post, we will discuss some of the array methods and how to use them to make your code more readable and concise.

First of all, I want to add that every array method uses the callback pattern. We’ll do a post on this pattern later, when discussing Asynchronous JavaScript, but for now you need to know that callbacks in these functions are called for every item in the array.

The easiest array method is called forEach and will just iterate over every item in the array.

	[1, 2, 3].forEach(function (item) { console.log(item); });

Most people will recognize this method. It iterates over every item and does nothing with the return value you provide. What most programmers don’t know is that you have some additional features in forEach.

	[1, 2, 3].forEach(function (item, index, array) { this.log(item);  }, console);

The forEach function lets you set the functions context (= this, more later) as well. In the previous example I injected console as the ‘this’ value in callback function.

But beware:

	function hasNumber (arr, number) {
		arr.forEach(function (item) { 
			if (item === number) return true; 
		});
	}

While this code might look okay, you must know that JavaScript’s forEach is still a callback function. Returning the value true inside the callback won’t result in the global function (hasNumber) to return true. You should refactor this code to

	function hasNumber (arr, number) {
		var found = false;
		arr.forEach(function (item){ if (item === number) found = true; });
		return found;
	}

By using the some-method you will get an even easier result, but more about that in a future post.