<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[Taku Uechi]]></title><description><![CDATA[Learning by teaching.]]></description><link>https://takuu.me/</link><generator>Ghost 0.7</generator><lastBuildDate>Thu, 20 Aug 2026 08:04:53 GMT</lastBuildDate><atom:link href="https://takuu.me/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[Exploring Next.js 13: App Router and Best Practices]]></title><description><![CDATA[<h1 id="exploringnextjs13approuterandbestpractices">Exploring Next.js 13: App Router and Best Practices</h1>

<p>Next.js has been my go-to React framework for applications where SEO, server-side rendering, and performance matter. Next.js 13 introduced one of the biggest changes to the framework with the App Router, React Server Components, and a much clearer separation</p>]]></description><link>https://takuu.me/exploring-next-js-13-app-router-and-best-practices/</link><guid isPermaLink="false">a3f9a536-524e-4262-92ca-8b4017e2a623</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Sat, 23 Oct 2021 21:58:00 GMT</pubDate><content:encoded><![CDATA[<h1 id="exploringnextjs13approuterandbestpractices">Exploring Next.js 13: App Router and Best Practices</h1>

<p>Next.js has been my go-to React framework for applications where SEO, server-side rendering, and performance matter. Next.js 13 introduced one of the biggest changes to the framework with the App Router, React Server Components, and a much clearer separation between server and client-side code.</p>

<p>When I originally started working with the App Router, though, it still felt fairly early. The architecture made a lot of sense, but there were definitely rough edges—especially around third-party libraries, serverless deployments, and figuring out where the server/client boundary should live.</p>

<p>After working with it, here are a few things I learned and some practices I found useful.</p>

<h2 id="proceedwithcaution">Proceed with Caution</h2>

<h3 id="1prismaandserverless">1. Prisma and Serverless</h3>

<p>If you're using Prisma with a serverless Next.js application, it's worth understanding how your database connections are being managed.</p>

<p>Traditional database connection pooling doesn't always map cleanly to serverless environments. When functions scale horizontally, it's possible to create significantly more database connections than expected.</p>

<p>This isn't necessarily a Next.js-specific problem, but the App Router makes it very easy to perform database operations directly inside server components, route handlers, and server-side functions, so it's something you need to think about early.</p>

<p>For production applications, make sure your database architecture is designed for the environment you're deploying into rather than assuming the same configuration you would use on a long-running Node.js server.</p>

<h3 id="2cloudflarepagescompatibility">2. Cloudflare Pages Compatibility</h3>

<p>Another issue I ran into early was deployment compatibility with Cloudflare Pages.</p>

<p>Next.js tends to move quickly and historically many hosting platforms haven't supported every Next.js feature at exactly the same time. Features that work seamlessly on Vercel may require additional configuration—or may not immediately be supported—on other platforms.</p>

<p>If you're deploying Next.js outside of Vercel, I recommend verifying support for the specific features you're using, especially:</p>

<ul>
<li>Server Components</li>
<li>Route Handlers</li>
<li>Middleware</li>
<li>Edge Runtime</li>
<li>Server-side rendering</li>
<li>Image optimization</li>
</ul>

<p>The framework may support something, but that doesn't automatically mean every hosting environment supports it in exactly the same way.</p>

<h2 id="handlingcssframeworksandreactlibraries">Handling CSS Frameworks and React Libraries</h2>

<p>One of the bigger mental shifts with the App Router is understanding the separation between Server Components and Client Components.</p>

<p>A lot of existing React libraries were originally designed around the assumption that everything runs in the browser. That assumption doesn't always work with Server Components.</p>

<h3 id="1usinguseclient">1. Using <code>"use client"</code></h3>

<p>Certain component libraries require the <code>"use client"</code> directive because they depend on browser APIs, React state, context, or other client-side functionality.</p>

<p>For example:</p>

<p>```tsx
"use client";</p>

<p>import { Button } from "@mui/material";</p>

<p>export default function MyButton() { <br>
  return <button>Click Me</button>;
}</p>]]></content:encoded></item><item><title><![CDATA[Immutable.js, the 80/20 Rule for React and Redux]]></title><description><![CDATA[<p>I've scoured the internet for some basic information on Immutable.js to help with the performance on some of my React applications.  But most only cover some of the basics or examples that don't use data structures that are common in most API.</p>

<p>Luckily for most coming from a functional</p>]]></description><link>https://takuu.me/immutable-js-the-80-20-rule-for-react-and-redux/</link><guid isPermaLink="false">2d33845f-a61b-49ed-91e1-738cc4bad938</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Sun, 25 Feb 2018 02:04:23 GMT</pubDate><content:encoded><![CDATA[<p>I've scoured the internet for some basic information on Immutable.js to help with the performance on some of my React applications.  But most only cover some of the basics or examples that don't use data structures that are common in most API.</p>

<p>Luckily for most coming from a functional programming background, (in JS, those familiar with lodash or underscore) the conceptual mental models and DSL's are relatively the same in Immutable.js.</p>

<p>First we have to understand the two main data structures: Map and List</p>

<h5 id="map">Map</h5>

<pre><code class="language-javascript">const map = Immutable.Map({ id: 1, name: 'John' });  
map.get('name') == 'John'; // true  
map.set('name', 'Mike');  
map.get('name') == 'Mike'; // true  
</code></pre>

<h5 id="list">List</h5>

<pre><code class="language-javascript">const list = Immutable.List([5, 20, 101];  
list.get(1) == 20; // true  
list.set(0, 9);  
list.get(0) == 9; // true  
list.set(4, 30);  
list.toJS(); // [9, 20, 101, undefined, 30]  
</code></pre>

<p>Converting to Immutable.js, fromJS magically detects the proper data structure to convert to.  In this example, Immutable.js knows to create a <strong>List</strong> of <strong>Map</strong> from an Array of Objects.  </p>

<pre><code class="language-javascript">const data = [ { id: 1, name: "John" }, { id: 2, name: "Adam" } ];  
const magic = Immutable.fromJS(data);

Immutable.List.isList(magic); // true  
Immutable.Map.isMap(magic.get(0)); // true
</code></pre>

<p>Of course, this can done manually as shown below</p>

<pre><code class="language-javascript">const result = [ { id: 1, name: "John" }, { id: 2, name: "Adam" } ];

const magic = Immutable.fromJS(result);

let list = Immutable.List();  
result.map((item, index) =&gt; { list = list.set(index, Immutable.Map(item))});  
Immutable.is(list, magic); // true,  
</code></pre>

<p>Okay, with these basic data structure building blocks, lets build a basic redux store using Immutable.js</p>

<p>Let's take a look at this Person reducer using <strong>List</strong> and <strong>Map</strong>  </p>

<pre><code class="language-javascript">const initialState = Immutable.List([  
  Immutable.Map({ id: 1, name: "John Snow", title: "King of the North" }), 
  Immutable.Map({ id: 2, name: "Adam", title: "Butcher" })
]);
function personReducer(state = initialState, action) {  
  switch (action.type) {
    case FETCH_ALL_PEOPLE:  // O(n)
      action.payload.map((item, index) =&gt; { 
        state = state.set(index, Immutable.Map(item));
      });
      // OR state = Immutable.fromJS(action.payload);
      return state;
    case FETCH_ALL_KINGS: // O(n^2)
      action.payload.map((king, index) =&gt; {
        const index = state.findIndex((item) =&gt; {
          return item.get('id') === king.id;
        });
        if ( index &gt;= 0 ) {
          state = state.set(index, Immutable.Map(king));
        } else {
          state.push(Immutable.Map(king));
        }
      });
      return state;
    case CREATE_PERSON: // O(1)
      return state.push(Immutable.Map(action.payload));
    case GET_PERSON: // O(n)
      const index = state.findIndex((item) =&gt; {
        return item.get('id') === action.payload.id;
      });
      if ( index &gt;= 0 ) {
        return state.update(index, (person) =&gt; {
          return person.set('name', action.payload.name);
        });
      } else {
        state.push(Immutable.Map(action.payload));
      }
      return state;
    case DELETE_PERSON: // O(n)
      const index = state.findIndex((item) =&gt; {
        return item.get('id') === action.payload.id;
      });
      return state.delete(index);
    case UPDATE_PERSON: // O(n)
      const index = state.findIndex((item) =&gt; {
        return item.get('id') === action.payload.id;
      });
      if ( index &gt;= 0 ) {
        state = state.set(index, Immutable.Map(action.payload));
      }
      return state;
    default:
      return state;
  }
}
</code></pre>

<p>Things are okay here except when we <code>FETCH_ALL_KINGS</code> and get O(n^2) by trying to combine an Array with a <strong>List</strong>.  We also have the following sprinkled in the code to check for duplicates which makes those cases a minimum of O(n) complexity</p>

<pre><code class="language-javascript">const index = state.findIndex((item) =&gt; {  
  return item.get('id') === action.payload.id;
});
</code></pre>

<h5 id="set">Set</h5>

<p><strong>Set</strong> duplicate checks are done very efficiently.  Lets rewrite the above code using <strong>Set</strong> instead of <strong>List</strong></p>

<pre><code class="language-javascript">const initialState = Immutable.Set([  
  Immutable.Map({ id: 1, name: "John Snow", title: "King of the North" }), 
  Immutable.Map({ id: 2, name: "Adam", title: "Butcher" })
]);
function personReducer(state = initialState, action) {  
  switch (action.type) {
    case FETCH_ALL_PEOPLE:  // O(nlogn)
    case FETCH_ALL_KINGS:  // O(nlogn)
      action.payload.map((item, index) =&gt; { 
        state = state.add(Immutable.Map(item));
      });
      return state;
    case CREATE_PERSON: // O(logn)
    case GET_PERSON: // O(logn)
      return state.add(Immutable.Map(action.payload));
    case DELETE_PERSON: // O(n)
      return state.delete(Immutable.Map(action.payload));
    case UPDATE_PERSON: // O(n)
      // This is a combo of DELETE_PERSON then CREATE_PERSON
      const found = state.find((person) =&gt; {
        return action.payload.id == person.get('id');
      });
      if (found) {
       state = state.delete(Immutable.Map(found));
       state = state.add(Immutable.Map(action.payload));
      }
      return state;
    default:
      return state;
  }
}
</code></pre>

<p>The code <code>state.add(Immutable.Map(action.payload));</code> checks for duplicates and if it does't exist, it adds it to the <strong>Set</strong>.  Similarly, <code>state.delete(Immutable.Map(action.payload))</code> is able to find the same data objects and delete it properly.</p>

<p>With this, you'll notice that the worse efficiency is at O(nlogn) which is a great trade off vs O(n^2).  The code is also more clean and readable.  A drawback of <strong>Set</strong> is that it isn't ordered like <strong>List</strong> so if order isn't important, the tradeoffs are worth it.</p>

<h5 id="record">Record</h5>

<p>If you noticed with <strong>Map</strong> <code>person.get('name')</code> isn't nearly as elegant as <code>person.name</code> in vanilla javascript on top of also losing a lot of the object syntactic sugar ES6+ provides.  Luckily Immutable.js provides the data structure <strong>Record</strong>, which is essentially <strong>Map</strong> but can be treated like a javascript object</p>

<pre><code class="language-javascript">const Person = Immutable.Record({ id: "", name: "" });  
const person = new Person({ id: 1, name: "John Snow" });

person.name // "John Snow"  
const { name } = person;  // name = "John Snow"  
</code></pre>

<p>We just covered the basics of <strong>Map</strong>, <strong>List</strong>, <strong>Set</strong> and <strong>Record</strong>. These data structures is just the tip of the iceberg but should be a great starting point for Immutable.js</p>]]></content:encoded></item><item><title><![CDATA[Some simple AI]]></title><description><![CDATA[<p>I've seen some impressive demonstrations of machine learning and am definitely not claiming this as one.  But I'm pretty proud of a kid I've been tutoring for a quite sometime now.</p>

<p>We created a simple simulation where a "muncher" would randomly move either left, right or jump to eat the</p>]]></description><link>https://takuu.me/some-simple-machine-learning-2/</link><guid isPermaLink="false">ce42356e-0578-4c28-8b33-3448d9b8ee93</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Wed, 01 Jun 2016 23:09:16 GMT</pubDate><content:encoded><![CDATA[<p>I've seen some impressive demonstrations of machine learning and am definitely not claiming this as one.  But I'm pretty proud of a kid I've been tutoring for a quite sometime now.</p>

<p>We created a simple simulation where a "muncher" would randomly move either left, right or jump to eat the randomly placed falling food.  Through many iterations, the muncher would figure out the most efficient way to eat the most amount of food.</p>

<p>In the beginning, the muncher would aimlessly move around as shown below (muncher is the green dot, food is the falling blue dot):</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/BttWhfkG1B0" frameborder="0" allowfullscreen></iframe>

<p>But after sometime, the muncher started to figure out a more efficient way to get more and more food:</p>

<iframe width="560" height="315" src="https://www.youtube.com/embed/OoZfRQuXEAw" frameborder="0" allowfullscreen></iframe>]]></content:encoded></item><item><title><![CDATA[Share data models in Mongoose with your Frontend]]></title><description><![CDATA[<p>In order to share a data models between technologies (ex: backend and frontend), the languages need to interpret the data to a common format.  Most of the time, this boils down to converting/extacting a JSON object model.</p>

<p>Example of a shared JSON between the backend and frontend:  </p>

<pre><code>// file: shared/</code></pre>]]></description><link>https://takuu.me/share-data-models-throughout-your-application/</link><guid isPermaLink="false">c0e2cfce-5a41-4382-936d-fa2d830466d4</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Sat, 19 Mar 2016 20:46:04 GMT</pubDate><content:encoded><![CDATA[<p>In order to share a data models between technologies (ex: backend and frontend), the languages need to interpret the data to a common format.  Most of the time, this boils down to converting/extacting a JSON object model.</p>

<p>Example of a shared JSON between the backend and frontend:  </p>

<pre><code>// file: shared/models/player.js
var Player {  
  league: { type: 'id', ref: 'League' },
  division: { type: 'id', ref: 'Division' },
  team: { type: 'id', ref: 'Team' },
  name: { type: 'string', default: '' },  
  created: { type: 'date', default: Date.now },
  updated: { type: 'date', default: Date.now }
};
export default Player;  
</code></pre>

<p>In case if you didn't notice, this looks exceptional similar to a Mongoose Schema Model.  The main difference is the ObjectId is replaced with the string 'id' and all the other types are now relagated to strings too for consistency:</p>

<pre><code>// file: api/utils.js
import mongoose from 'mongoose';  
var Schema = mongoose.Schema;  
import _ from 'lodash';

let mongooseify = function(json) {

  let result = {};
  _.map(Object.keys(json), (key) =&gt; {
    let property = _.cloneDeep(json[key]);
    let type;
    switch(property.type) {
      case 'id':
        type = Schema.ObjectId;
        break;
      case 'number':
        type = Number;
        break;
      case 'string':
        type = String;
        break;
      case 'date':
        type = Date;
        break;
      default:
        break;
    }
    result[key] = _.assign({}, property, {type});
  });

  return result;
};
</code></pre>

<p>Note: (This can be extended to add additional types) <br>
And finally, create the Mongoose Model:</p>

<pre><code class="language- javascript">// file: api/models/player.model.js
'use strict';  
import mongoose from 'mongoose';  
var Schema = mongoose.Schema;  
import player from '../../shared/models/player';  
import utils from '../utils';

/**
 * Player Schema
 */
var PlayerSchema = new Schema(utils.mongooseify(player));

module.exports = mongoose.model('Player', PlayerSchema);
</code></pre>]]></content:encoded></item><item><title><![CDATA[Remove duplicates from MongoDB]]></title><description><![CDATA[<p>As of version 2.x, MongoDB dropped support for dropDups due to it's dangerous nature of not knowing which item to remove (We don't want to break the dependency chain do we?)</p>

<p>Given the simple object of a Sports Team  </p>

<pre><code>{
  "name": "Knights",
  "city": "Los Angeles",
  "state": "CA"
}
</code></pre>

<p>We want to</p>]]></description><link>https://takuu.me/remove-duplicates-from-mongodb/</link><guid isPermaLink="false">255e9c80-f409-4ea2-892e-2fe9dd3da49b</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Wed, 09 Mar 2016 17:31:21 GMT</pubDate><content:encoded><![CDATA[<p>As of version 2.x, MongoDB dropped support for dropDups due to it's dangerous nature of not knowing which item to remove (We don't want to break the dependency chain do we?)</p>

<p>Given the simple object of a Sports Team  </p>

<pre><code>{
  "name": "Knights",
  "city": "Los Angeles",
  "state": "CA"
}
</code></pre>

<p>We want to remove all duplicates that have the same combination of name, city and state.  To view all duplicates of this combination, run a map reduce in MongoDB:</p>

<pre><code>db.getCollection('teams').aggregate(  
    { $match: { 
        name: { $ne: ''},
        city: { $ne: ''},
        state: { $ne: ''}
    }},
    { $group: {
        _id: { name: "$name", city: "$city", state: "$state"},
        count: { $sum: 1},
        dups: { $push: "$_id"}
    }},
    { $match: {
        count: { $gt: 1}
    }}
)
</code></pre>

<p>The results should show if there are any duplicate combinations.</p>

<p>To remove the duplicates run:  </p>

<pre><code>var duplicates = [];

db.getCollection('teams').aggregate([  
  { $match: { 
      name: { $ne: ''},
      city: { $ne: ''},
      state: { $ne: ''}
  }},
  { $group: { 
      _id: { name: "$name", city: "$city", state: "$state"},
      count: { $sum: 1},
      dups: { $push: "$_id"}, 

  }}, 
  { $match: { 
      count: { $gt: 1}
  }}
])               
.forEach(function(doc) {
    doc.dups.shift();      
    doc.dups.forEach( function(dupId){ 
        duplicates.push(dupId);
        }
    )    
})


db.getCollection('teams').remove({_id:{$in:duplicates}})  
</code></pre>

<p>A caution to note, this script does not check the dependencies before deleting.  So use at your own risk.</p>]]></content:encoded></item><item><title><![CDATA[The Problem with async await with Lodash]]></title><description><![CDATA[<p>I recently was writing a web scraper and ran into an issue with async await.  It's not so much a problem with how it works.  In fact I love the new ES2016/ES7 proposal.  It's just the current tools and libraries will need to adapt to work in parallel with</p>]]></description><link>https://takuu.me/the-problem-with-async-await/</link><guid isPermaLink="false">1df9f1a8-7460-41cb-8caf-e567fa2c2915</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Mon, 29 Feb 2016 17:20:40 GMT</pubDate><content:encoded><![CDATA[<p>I recently was writing a web scraper and ran into an issue with async await.  It's not so much a problem with how it works.  In fact I love the new ES2016/ES7 proposal.  It's just the current tools and libraries will need to adapt to work in parallel with it.  Working with Lodash with async await is just not feasible at the moment.</p>

<p>Fetching for a list of teams then fetching for their list of players returns a list of promises in the below example:</p>

<pre><code class="language-javascript">async function getTeams() {  
  var teamList = _.map(await getTeamList(), async (team) =&gt; {
    team.players = await getPlayerList(team.teamId);
  });

  return teamList;
}

getTeams().then((data)=&gt; {  
  console.log('Array of promises...', data);
});
</code></pre>

<p>This isn't too surprising since async functions returns a promise and mapping through them simple just returns the list of them.  But the problem lies in the way Lodash/Underscore implements iterating through lists.  If you need to run an await, it needs to be inside an async function and cannot be inside a normal function(or arrow function for that matter).  So iterating through a list and handling promises through a callback function becomes much more of an issue.</p>

<p>The best way I found to handle this issue to to iterate without callback functions using the old school For Loops.</p>

<pre><code class="language-javascript">async function getTeams() {  
  var teamList = await getTeamList();
  for(let i=0; i&lt;teamList.length; i++) {
    let team = teamList[i];
    team.players = await getPlayerList(team.teamId);
  }
  return teamList;
}

getTeams().then((data)=&gt; {  
  console.log('Array of teams with players!', data);
});
</code></pre>]]></content:encoded></item><item><title><![CDATA[Creating unit tests in AngularJS]]></title><description><![CDATA[<p>Unit testing can be one of the most disliked part of the software development.  John Papa came forward and stated that he dislikes writing tests because of the amount of setup required to write the first "it" (source: <a href="http://devchat.tv/adventures-in-angular/025-aia-testing-with-ward-bell">http://devchat.tv/adventures-in-angular/025-aia-testing-with-ward-bell</a>).  I can definitely relate and I figure</p>]]></description><link>https://takuu.me/creating-unit-tests-in-angularjs/</link><guid isPermaLink="false">a1156509-3dc3-4c64-871c-316d672d309d</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Tue, 03 Mar 2015 05:40:38 GMT</pubDate><content:encoded><![CDATA[<p>Unit testing can be one of the most disliked part of the software development.  John Papa came forward and stated that he dislikes writing tests because of the amount of setup required to write the first "it" (source: <a href="http://devchat.tv/adventures-in-angular/025-aia-testing-with-ward-bell">http://devchat.tv/adventures-in-angular/025-aia-testing-with-ward-bell</a>).  I can definitely relate and I figure I should share some tips <br>
to reduce the boilerplate for writing tests.</p>

<p><strong>Why we should</strong></p>

<p>Writing tests help write more testable code which usually translates to more simple code and allows for easier refactoring.  It also instills confidence in the developers to deploy their code that are unit tested.</p>

<ul>
<li><p>Reduce time to first "it"</p></li>
<li><p>Maintainability</p></li>
<li><p>Readability while being more declarative instead of imperative</p></li>
</ul>

<p><strong>Tooling</strong></p>

<ul>
<li>Karma</li>
<li>Jasmine</li>
</ul>

<p><strong>Ways to reduce boilerplate</strong></p>

<ul>
<li>if using Jasmine, nested describes helps write clearer tests.  By nesting describes, we can bundle similar tests as
well as bundle similar boilerplate in the beforeEach and write leaner "it" statements. (<a href="http://devchat.tv/adventures-in-angular/026-aia-testing-tools">http://devchat.tv/adventures-in-angular/026-aia-testing-tools</a>)  </li>
<li>reduce mocks (refer to post on TDD is dead?)
<ul><li>Less global states</li>
<li>More modular code</li></ul></li>
<li>automate ways to run tests
<ul><li>karma TDD, by using PhantomJS.  Setup to run on file save.</li></ul></li>
</ul>

<p><strong>Plugins</strong></p>

<ul>
<li>promote ng-html2js</li>
<li>promote your ng-request2js</li>
<li>promote your html-to-json-array</li>
</ul>

<h5 id="testingdirectivesgeneral">Testing directives (general)</h5>

<pre><code class="language-javascript">//directive someDirective
angular.module('someDirective')  
  .directive('someDirective', someDirective);
function someDirective() {  
  return {
    restrict: 'E',
    scope: {
      personName: '='
    },
    template: '&lt;div&gt;{{welcomeMessage}}&lt;/div&gt;',
    link: function(scope, element, attrs) {
      scope.welcomeMessage = 'Hello ' + scope.personName;
    }
  }
};
</code></pre>

<pre><code class="language-javascript">// typical Directive boilerplate should go here
describe('someDirective', function () {  
  beforeEach(module('app'));
  var $scope, $compile, $rootScope, element;

  beforeEach(inject(function($injector) {
    $rootScope = $injector.get('$rootScope');
    $compile = $injector.get('$compile');
    $scope = $rootScope.$new();

    element = angular.element('&lt;some-directive person-name="John"&gt;&lt;/some-directive&gt;');
    $compile(element)($scope);
  }));

  it('should welcome the user', function() {
      expect(element.html()).toContain('Hello John');
  });

});
</code></pre>

<h5 id="testingdirectivescontroller">Testing directives (controller)</h5>

<pre><code class="language-javascript">// directive someDirective
angular.module('app', []);  
angular.module('app')  
  .directive('someDirective', someDirective);

function someDirective() {  
  return {
    restrict: 'E',
    scope: {},
    template: '&lt;div&gt;{{welcomeMessage}}&lt;/div&gt;',
    controller: function($scope) {
      $scope.welcome = function(name) {
        $scope.welcomeMessage = 'Hello ' + name;
      }
    }
  }
}
</code></pre>

<p><strong>test directive controller scope</strong></p>

<pre><code class="language-javascript">describe('someDirective', function () {  
  beforeEach(module('app'));
  var $scope, $compile, $rootScope, element;

  beforeEach(inject(function($injector) {
    $rootScope = $injector.get('$rootScope');
    $compile = $injector.get('$compile');
    $scope = $rootScope.$new();

    element = angular.element('&lt;some-directive &gt;&lt;/some-directive&gt;');
    $compile(element)($scope);
  }));

  it('should welcome the user', function() {
      var scope = element.isolateScope();
      scope.welcome('John');
      $scope.$digest();
      expect(element.html()).toContain('Hello John');
  });
</code></pre>

<p><strong>test directive controller this</strong></p>

<pre><code class="language-javascript">// directive someDirective
angular.module('app', []);  
angular.module('app')  
  .directive('someDirective', someDirective);

function someDirective() {  
  return {
    restrict: 'E',
    scope: {},
    template: '&lt;div&gt;{{welcomeMessage}}&lt;/div&gt;',
    controller: function($scope) {
      this.welcome = function(name) {
        $scope.welcomeMessage = 'Hello ' + name;
      }
    }
  }
};
</code></pre>

<pre><code class="language-javascript">describe('someDirective', function () {  
  beforeEach(module('app'));
  var $scope, $compile, $rootScope, element, controller;

  beforeEach(inject(function($injector) {
    $rootScope = $injector.get('$rootScope');
    $compile = $injector.get('$compile');
    $scope = $rootScope.$new();

    element = angular.element('&lt;some-directive &gt;&lt;/some-directive&gt;');
    $compile(element)($scope);

    $rootScope.$apply();
    controller = element.controller('someDirective');
  }));

  it('should welcome the user', function() {
      controller.welcome('John');
      $scope.$digest();
      expect(element.html()).toContain('Hello John');
  });
</code></pre>

<p><strong>Testing Services</strong></p>

<pre><code class="language-javascript">// someService code here
angular.module('app', []);  
angular.module('app')  
  .factory('someService', someService);

function someService() {  
  var welcomeMessage = '';
  var MessageCreator = function() {
    this.welcome = function(name) {
      welcomeMessage = 'Hello ' + name;
    };

    this.getWelcomeMessage = function() {
      return welcomeMessage;
    };
  }
  return MessageCreator;
};
</code></pre>

<pre><code class="language-javascript">// test code here
describe('someService', function() {  
  beforeEach(module('app'));
  var $rootScope, $scope, $scope;
  beforeEach(inject( function ($injector) {
    $rootScope = $injector.get('$rootScope');
    someService = $injector.get('someService');
    $scope = $rootScope.$new();
  }));

  it('should create new someService object', function() {
    var service = new someService();
    expect(someService).toBeDefined();
    expect(typeof someService).toBe('object');
  });

  it('should create a welcome message', function() {
    var service = new someService();
    service.welcome('John');
    expect(service.getWelcomeMessage()).toEqual('Hello John');
  });
}
</code></pre>

<p><strong>Testing Controllers</strong></p>

<pre><code class="language-javascript">// someController code here

angular.module('app', []);  
angular.module('app')  
  .controller('SomeController', SomeController);
function SomeController($scope) {  
  $scope.welcome = "Welcome " + $scope.name;
}
</code></pre>

<pre><code class="language-javascript">// test code here
describe('someController', function(){  
  beforeEach(module('app'));
  var scope, ctrl;

  beforeEach(inject(function($controller, $rootScope) {
    $cope = $rootScope.$new();
    ctrl = $controller(someController, { $scope: scope });
  }));

  it('should change welcome message when name is set', function() {
    scope.name = "John";
    scope.$digest();
    expect(scope.welcome).toBe("Welcome John");
  });
});
</code></pre>]]></content:encoded></item><item><title><![CDATA[Favorite ES6 Features]]></title><description><![CDATA[<p>With ES6 standardized and popular transpilers like 6to5 making its emergence, I figure to list out some of my favorite ES6 features.</p>

<h4 id="arrowfunction">Arrow Function</h4>

<p>Without a doubt, the arrow function is my favorite and probably one of the most commonly seen peppered around in github source code.  It's pure syntactic</p>]]></description><link>https://takuu.me/favorite-es6-features/</link><guid isPermaLink="false">d7ce35d8-1446-451e-9f31-df3267bb2133</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Tue, 10 Feb 2015 07:02:29 GMT</pubDate><content:encoded><![CDATA[<p>With ES6 standardized and popular transpilers like 6to5 making its emergence, I figure to list out some of my favorite ES6 features.</p>

<h4 id="arrowfunction">Arrow Function</h4>

<p>Without a doubt, the arrow function is my favorite and probably one of the most commonly seen peppered around in github source code.  It's pure syntactic sugar but it's simplicity in how it handles the clunkiness of the <code>this</code> keyword definitely makes this my favorite.</p>

<p><strong>Before:</strong></p>

<pre><code class="language-javascript">var User: {  
  name: "John",
  welcome: function() {
    var that = this;
    request.get(url, function(res) {
      that.name = res.name;
    });
  }
}
</code></pre>

<p><strong>With ES6:</strong></p>

<pre><code class="language-javascript">var User: {  
  name: "John",
  welcome: function() {
    request.get(url, res =&gt; this.name = res.name );
  }
}
</code></pre>

<h4 id="promises">Promises</h4>

<p>There's a lot of libraries provide the promises functionality like Q, Bluebird and in AngularJS but I was hoping for a more native implementation to quiet all the naysayers in regards to callback hell.  Finally, that day has come.</p>

<p><strong>Before:</strong></p>

<pre><code class="language-javascript">async1(function () {  
  async2(function () {
    async3(function () {
      async4(function () {
      })
    })
  })
})
</code></pre>

<p><strong>With ES6:</strong></p>

<pre><code class="language-javascript">var async1 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async2 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async3 = new Promise(function(resolve, reject) {  
  resolve(1);
});
var async4 = function() {console.log('async4');}

async1.then(nosync).then(async3).then(async4);
</code></pre>

<h4 id="let">Let</h4>

<p>Javascript has an uncanny valley effect for most developers coming from a C and Java background.  It looks like Java but it doesn't behave like it.  Most developers learn the hard way through hard to find bugs.  One of the bugs that get most developers is scoping</p>

<p><strong>Before:</strong></p>

<pre><code class="language-javascript">for(var i=0; i&lt;10; i++) {  
// some implementation
}

console.log(i);  
// 10;
</code></pre>

<p><strong>With ES6:</strong></p>

<pre><code class="language-javascript">for(let i=0; i&lt;10; i++) {  
// some implementation
}

console.log(i);  
// i is not defined
</code></pre>

<h4 id="defaultparameters">Default parameters</h4>

<p>Although I wasn't too fond of CoffeeScript (I prefer TypeScript), one feature I liked a lot about CoffeeScript was the ability to set default parameters.  It was more declarative and reduced some plumbing when passing in parameters.</p>

<p><strong>Before:</strong></p>

<pre><code class="language-javascript">function handler(name, message) {  
  if (typeof name === "undefined") name = "John";
  if (typeof message === "undefined") message = "Hello";

  console.log(message + " " + name);
}
</code></pre>

<p><strong>With ES6:</strong></p>

<pre><code class="language-javascript">function handler(name = "John", message = "Hello") {  
  console.log(message + " " + name);
}
</code></pre>

<h4 id="destructuring">Destructuring</h4>

<p>Once upon a time, I used to write in Perl.  It was bashed for it's archaic and unreadable syntax (Write once, read never!).  But quite honestly, if your developers had enough discipline, you can pump out pretty maintainable code.  One such feature that I missed from Perl was Destructuring.</p>

<p><strong>Before:</strong></p>

<pre><code class="language-javascript">var list = [1,2,3];  
var a = list.shift();  
list.shift();  
var b = list.shift();  
console.log(a,b);  
// 1 3
</code></pre>

<p><strong>With ES6:</strong></p>

<pre><code class="language-javascript">var [a, , b] = [1,2,3];  
console.log(a,b);  
// 1 3
</code></pre>]]></content:encoded></item><item><title><![CDATA[Projects]]></title><description><![CDATA[<p><a href="http://www.famcentric.com">FamCentric</a> [Node, Express, MongoDB, Angular, Bootstrap]</p>

<p>Show and rate schools K through elementary schools as well as language schools.  Site built using the MEAN stack.  Build with a CMS, scraper, OAuth login, search, rating and review features.</p>

<p><a href="https://github.com/tym2/leaguer">Leaguer</a> [Node, Express, MongoDB, React, Reflux, Bootstrap]</p>

<p>Isomorphic web application built with both</p>]]></description><link>https://takuu.me/projects/</link><guid isPermaLink="false">80854feb-b1e4-4d32-b9f1-16b1ff39dfe0</guid><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Tue, 20 Jan 2015 03:25:32 GMT</pubDate><content:encoded><![CDATA[<p><a href="http://www.famcentric.com">FamCentric</a> [Node, Express, MongoDB, Angular, Bootstrap]</p>

<p>Show and rate schools K through elementary schools as well as language schools.  Site built using the MEAN stack.  Build with a CMS, scraper, OAuth login, search, rating and review features.</p>

<p><a href="https://github.com/tym2/leaguer">Leaguer</a> [Node, Express, MongoDB, React, Reflux, Bootstrap]</p>

<p>Isomorphic web application built with both server-side rendering and a single page application.  Display player and team trending strengths and other teams weaknesses.</p>

<p><strong>NPM Modules</strong></p>

<p><a href="https://www.npmjs.com/package/html-scripts-to-array">html-scripts-to-array</a></p>

<p>Extracts HTML scripts source links to a JSON array.</p>

<p><a href="https://www.npmjs.com/package/karma-ng-request2js-preprocessor">karma-ng-request2js-preprocessor</a></p>

<p>A Karma plugin. Save AngularJS $http JSON requests to JavaScript</p>]]></content:encoded></item><item><title><![CDATA[Creating Infinite Scroll in AngularJS]]></title><description><![CDATA[<p>You're live! Nice. We've put together a little post to introduce you to the Ghost editor and get you started. You can manage your content by signing in to the admin area at <code>&lt;your blog URL&gt;/ghost/</code>. When you arrive, you can select this post from a list</p>]]></description><link>https://takuu.me/welcome-to-ghost/</link><guid isPermaLink="false">e40eb2fe-6aaa-406a-856b-42e08f18599a</guid><category><![CDATA[Getting Started]]></category><dc:creator><![CDATA[Taku Uechi]]></dc:creator><pubDate>Wed, 17 Sep 2014 00:55:31 GMT</pubDate><content:encoded><![CDATA[<p>You're live! Nice. We've put together a little post to introduce you to the Ghost editor and get you started. You can manage your content by signing in to the admin area at <code>&lt;your blog URL&gt;/ghost/</code>. When you arrive, you can select this post from a list on the left and see a preview of it on the right. Click the little pencil icon at the top of the preview to edit this post and read the next section!</p>

<h2 id="gettingstarted">Getting Started</h2>

<p>Ghost uses something called Markdown for writing. Essentially, it's a shorthand way to manage your post formatting as you write!</p>

<p>Writing in Markdown is really easy. In the left hand panel of Ghost, you simply write as you normally would. Where appropriate, you can use <em>shortcuts</em> to <strong>style</strong> your content. For example, a list:</p>

<ul>
<li>Item number one</li>
<li>Item number two
<ul><li>A nested item</li></ul></li>
<li>A final item</li>
</ul>

<p>or with numbers!</p>

<ol>
<li>Remember to buy some milk  </li>
<li>Drink the milk  </li>
<li>Tweet that I remembered to buy the milk, and drank it</li>
</ol>

<h3 id="links">Links</h3>

<p>Want to link to a source? No problem. If you paste in url, like <a href="http://ghost.org">http://ghost.org</a> - it'll automatically be linked up. But if you want to customise your anchor text, you can do that too! Here's a link to <a href="http://ghost.org">the Ghost website</a>. Neat.</p>

<h3 id="whataboutimages">What about Images?</h3>

<p>Images work too! Already know the URL of the image you want to include in your article? Simply paste it in like this to make it show up:</p>

<p><img src="https://ghost.org/images/ghost.png" alt="The Ghost Logo"></p>

<p>Not sure which image you want to use yet? That's ok too. Leave yourself a descriptive placeholder and keep writing. Come back later and drag and drop the image in to upload:</p>

<h3 id="quoting">Quoting</h3>

<p>Sometimes a link isn't enough, you want to quote someone on what they've said. It was probably very wisdomous. Is wisdomous a word? Find out in a future release when we introduce spellcheck! For now - it's definitely a word.</p>

<blockquote>
  <p>Wisdomous - it's definitely a word.</p>
</blockquote>

<h3 id="workingwithcode">Working with Code</h3>

<p>Got a streak of geek? We've got you covered there, too. You can write inline <code>&lt;code&gt;</code> blocks really easily with back ticks. Want to show off something more comprehensive? 4 spaces of indentation gets you there.</p>

<pre><code>.awesome-thing {
    display: block;
    width: 100%;
}
</code></pre>

<h3 id="readyforabreak">Ready for a Break?</h3>

<p>Throw 3 or more dashes down on any new line and you've got yourself a fancy new divider. Aw yeah.</p>

<hr>

<h3 id="advancedusage">Advanced Usage</h3>

<p>There's one fantastic secret about Markdown. If you want, you can  write plain old HTML and it'll still work! Very flexible.</p>

<p><input type="text" placeholder="I'm an input field!"></p>

<p>That should be enough to get you started. Have fun - and let us know what you think :)</p>]]></content:encoded></item></channel></rss>