Polymer Nested Scoping

I’ve taken my first dive into Polymer and the uber intriguing Web Components concept. One of the first things I had issues with was availability of custom attributes passed into the component template.

This issue arises when you have nested, or child, templates. In the example below, you’ll notice I’ve several nested templates inside my polymer-element.

Note that in each child template I’m trying to print out {{myvar}}, which is a custom attribute. In the first, it simply doesn’t exist, but we’re golden in the second. Polymer docs have this to say:

If a <template> using a named scope contains child <template>s, all ancestor scopes are visible, up-to and including the first ancestor not using a named scope….

In other words:

  • If a template uses a named scope, its parent scope is visible.
  • If a template uses an unnamed scope, its parent scope is not visible.

See http://www.polymer-project.org/docs/…

For some reason, this just didn’t click for me on the first read through.

A named scope looks like this:

<template bind="{{foo as bar}}">

Where as an un-named looks like:

<template bind="{{foo}}">

In the latter, the scope is limited to foo; no access to any parent scope is allowed. But the above says even more. That scoping is inherited up through the child templates until it hits the first un-named scope, that’s important to remember.

JS Bin

De-Duplicating JavaScript Array of Objects

Yesterday I found I needed to de-duplicate an array of objects. The problem is, I needed to compare the objects in their entirety, not just by an individual key. I was quite surprised to find something was not already written up, and shared, on the interwebs.

Maybe it’s rare that one needs to get a unique array of objects by comparing the entire object. Or maybe it’s not very performant so folks don’t bother. Either way, here’s what I came up with. I hope you find it helpful. If you come up with a better method, please do let me know.

JS Bin

Cool Currency Focused JS Library

Just found accounting.js, which is a Javascript library “… for number, money and currency formatting …”. I love it so far. Check out the examples, then go check out the lib here and here.

// Default usage:

accounting.formatMoney(12345678); // $12,345,678.00

// European formatting (custom symbol and separators), could also use options object as second param:
accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99

// Negative values are formatted nicely, too:
accounting.formatMoney(-500000, "£ ", 0); // £ -500,000

// Simple `format` string allows control of symbol position [%v = value, %s = symbol]:
accounting.formatMoney(5318008, { symbol: "GBP",  format: "%v %s" }); // 5,318,008.00 GBP

Regular Expression in Array.indexOf()

A few minutes ago I found I needed to find the first index of an element in an array using RegEx. Unfortunately, such a tool is not in the JavaScript toolbox so without further delay, here’s what I came up with.

http://jsfiddle.net/CreativeNotice/66KKr/

/**
 * Regular Expresion IndexOf for Arrays
 * This little addition to the Array prototype will iterate over array
 * and return the index of the first element which matches the provided
 * regular expresion.
 * Note: This will not match on objects.
 * @param  {RegEx}   rx The regular expression to test with. E.g. /-ba/gim
 * @return {Numeric} -1 means not found
 */
if (typeof Array.prototype.reIndexOf === 'undefined') {
    Array.prototype.reIndexOf = function (rx) {
        for (var i in this) {
            if (this[i].toString().match(rx)) {
                return i;
            }
        }
        return -1;
    };
}

// Try it out

// Array of strings
// Should return 3
var test = ['foo', '-bar', 'droopy', 'dog'];
console.log( 'array of strings:', test.reIndexOf(/og/) );

// Array with numbers
// Should return 3
var test = ['foo', '-bar', '1', 2];
console.log( 'array with numbers:', test.reIndexOf(/2/) );

// Array with objects
// Should return 3
var test = ['foo', { 'test':'one' }, { 'test':2 }, 2];
console.log( 'array of obj:', test.reIndexOf(/2/) );

Javascript Money Format a Number

I’m constantly needing to format a number as currency for display in the UI.
Here’s a little prototype I whipped up to facilitate this. Currently it’s only working for US format, but should be pretty simple to modify. Please consider letting me know if you do modify it.

	/**
	 * formatMoney
	 * @param  {Numeric} len Length of decimals
	 * @param  {String}  sep Thousands seperator
	 * @param  {String}  dec Decimal seperator
	 * @param  {String}  sym Money symble
	 * @return {String}
	 */
	Number.prototype.formatMoney = function (len, sep, dec, sym)
	{
		// this number
		var num = this;

		// setup defaults
		len = (typeof len === 'undefined') ?  2  : len;
		sep = (typeof sep === 'undefined') ? ',' : sep;
		dec = (typeof dec === 'undefined') ? '.' : dec;
		sym = (typeof sym === 'undefined') ? '$' : sym;

		// Start formating
		// round up decimal to len specified
		num = num.toFixed( len ).toString();
		// add thousands seperator every third diget
		num = sym + num.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,'$1'+ sep);

		return num;
	};

And here it is minified:

Number.prototype.formatMoney=function(a,b,c,d){var e=this;return a=typeof a=="undefined"?2:a,b=typeof b=="undefined"?",":b,c=typeof c=="undefined"?".":c,d=typeof d=="undefined"?"$":d,e=e.toFixed(a).toString(),e=d+e.replace(/(\d)(?=(\d\d\d)+(?!\d))/g,"$1"+b),e}