More Power for Your ku4collections!

Recently, I posted about the NoSQL front-end storage afforded by ku4js-data. I discussed the awesome power of both storing and querying with this tool. I also shared how to find, insert, remove, update and even join! If you missed it, you can find that article here.

ku4collections are jam packed with awesome features, far too many to cram into one blog article. So, I thought why not follow up the last entry with yet another sweet feature for ku4collections that is too money to keep secret. The wicked awesome feature that we’ll look at today is the exec method.

The exec method is a excellent and useful feature that will allow you to extend ku4collections on the fly and beef up your query power simply by passing a strategy (a.k.a function) to execute on each item returned from your find query. Crazy power. Crazy simple.

And there is no better way to wrap our heads around how it works than diving right in and seeing it in action.

Let’s say that we have a system that we built for a car lot. In this system we maintain cars, plain and simple. Here are our cars:

VIN: 17H83SF839IXC3ND
Make: Honda
Model: Accord
Price: $25,000.00 USD
Miles: 32032

VIN: 6767SDF63JD63JKSD
Make: BMW
Model: 750i
Price: $93,000.00 USD
Miles: 28701

VIN: DU8S923UKSN89872
Make: Volvo
Model: S60
Price: $28,000.00 USD
Miles: 45098

VIN: 9S8DJ2L1JD7KS83LLS
Make: Chevrolet
Model: Silverado
Price: $42,000.00 USD
Miles: 13980

Let’s say that we want our users, the potential buyers, to be able to see how much a vehicle will cost them monthly if they take out a loan. Also, let’s say that we are offering a program where, if you take out a loan for your vehicle we will take $500.00 of the sticker price.

Okay, so first things first, lets create our cars collection:

var cars = $.ku4collection("cars").init([
 {
  vin: "17H83SF839IXC3ND",
  make: "Honda",
  model: "Accord",
  price: 25000,
  miles: 32032
 },
 {
  vin: "6767SDF63JD63JKSD",
  make: "BMW",
  model: "750i",
  price: 93000,
  miles: 28701
 },
 {
  vin: "DU8S923UKSN89872",
  make: "Volvo",
  model: "S60",
  price: 28000,
  miles: 45098
 },
 {
  vin: "9S8DJ2L1JD7KS83LLS",
  make: "Chevrolet",
  model: "Silverado",
  price: 42000,
  miles: 13980
 }
]).save();

DON’T FORGET TO SAVE!

And let’s just quick run a simple find query to make sure that we have what we expect.

cars.find();

Image

Okay, all looks good.

Next we will implement the promotion program that we are running: Take out a loan for a car and get $500.00 off of the sticker price!

We’re actually going to create a calculator class that performs the loan calculation for our promotion. Our loan calculator should be able to take a price, a down payment, an interest rate and a term (in months). Then, with that, it should calculate and return a monthly payment.

We can implement this loan calculator using simple JavaScript and give it just a little oomph by leveraging a pretty cool ku4js-kernel class.

function loanCalculator(interestRate, termInMonths, moneyDown) {
 this._interestRate = interestRate;
 this._termInMonths = termInMonths;
 this._moneyDown = moneyDown || 0;
}
loanCalculator.prototype = {
 calculate: function(price) {
  var PV = price - this._moneyDown,
      APR = this._interestRate / 12,
      T = this._termInMonths;
   return $.math.round((PV * APR) / (1-(Math.pow((1+APR), -T))), -2);
 }
};
$.loanCalculator = function(moneyDown, interestRate, term) {
 return new loanCalculator(moneyDown, interestRate, term);
};

A couple of contrived unit tests to ensure that all is working as expected:

function assertEqual(actual, expected) {
 console.log(actual, expected, actual === expected);
}
var testCalculator = $.loanCalculator(.07, 36, 500);
assertEqual(testCalculator.calculate(10500), 308.77);
assertEqual(testCalculator.calculate(12345), 365.74);
assertEqual(testCalculator.calculate(98765), 3034.14);

Image

Alright, everything is in place. Let’s turn-and-burn!

First, we will create our exec strategy (a.k.a function) that will calculate our promotional price and update our entities when we run our find query to include the promotional price and the total cost. It will also leverage the ku4js-kernel $.money class to format our amounts as money.

var userTerms = $.loanCalculator(.07, 60, 500);
function addPromotionPrice(item) {
 var promotionPrice = userTerms.calculate(item.price);
 item.promotionPrice = $.money(promotionPrice).toString();
 item.price = $.money(item.price).toString();
 item.totalCost = $.money(promotionPrice * 60).toString();
 return item;
}

And there we have it. We will be adding the “promotionPrice” and a “totalCost” as a property to each item in the return value of our query. We will also leverage the, always useful, ku4js-kernel money class to format our prices as cash.

It is important to know that the ku4collection exec strategy will always be a function that will be passed an individual item for each item that is found in your subsequent find query. The exec function will have an opportunity to operate on each and every item once. Your exec function must return a value, for it is this return value that you will receive in your find results. I repeat, the value that you return will be the value that is in the output of your find query.

So, with all of that said, are you ready? — Let’s give it a shot!

I should mention that our potential buyer is only interested in BMW and Volvo, therefore, we should only output those makes. They would also like to spend as little as possible, so, as a courtesy, and to improve the possibility that we make a sale, we will order our results by promotion price in ascending order to show the lowest priced cars first.

var results = cars.exec(addPromotionPrice)
                 .find({"$in":{"make":["BMW","Volvo"]}, 
                        "$orderby": {"promotionPrice": 1}});

Okay, we now have the results that we are looking for, how should we display them? How about we push them to the browser in some simple HTML. To do this lets use the, ever excellent $.str ku4js-kernel string utility. I won’t cover it in any detail in this article, but you can find some documentation on it here and other ku4* libraries on guthub.

First lets create our template:

var html = "",
    template = '<h1>{{make}} {{model}}</h1>' +
               '<h2>Monthly Payment: {{promotionPrice}}</h2>' +
               '<div>Sticker: {{price}}</div>' +
               '<div style="fontSize:8px">Total Cost: {{totalCost}}</div><hr/>';

ku4js-kernel has a great $.str.render method that takes a string and will replace all of the double curly brace values with the values in the second argument which is an object that should contain the keys that correspond with values between the double curly braces. More on this in another article.

Next lets leverage a ku4js-kernel $.list to iterate through our results, generate HTML and write it to the screen.

$.list(results).each(function(item) {
 html += $.str.render(template, item);
});

document.body.innerHTML = html;

Image

And there you have it! The ku4collection exec method.

Please, comment on and share this post with others if you enjoy it; follow @kodmunki on Twitter for regular updates on new developments, deployments, articles, and tools; and check out kodmunki™ on github for cool, managed, and tested kodmunki™ projects.

Thank you for reading, and as always, happy coding :{)}

 

Advertisements

Software development leaders at the forefront of the latest in technology. Whether implementing updates or integrating with existing technology; developing products that push the bleeding edge of the latest in tech; or developing open-source products, paving the way of future tech, kodmunki™ inspires innovation, elevates quality, and drives value to production. kodmunki™ are experts in web, mobile, and hybrid solutions development; local and distributed team management and collaboration; and fast, quality, successful product delivery, offering R&D, training, consulting, and development services. Contact us at info@kodmunki.com. Let's discuss your vision.

Tagged with: , , , , , , , ,
Posted in JavaScript, ku4js-data
One comment on “More Power for Your ku4collections!
  1. […] More Power for Your ku4collections! […]

Enjoy the read? -- Let us know.

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

kodmunki™ Tweets

Enter your email address and receive notifications of new kodmunki™ posts by email.

%d bloggers like this: