From 55bb2b182ebf87998145743c9cee46d414bd82c9 Mon Sep 17 00:00:00 2001 From: Radek Stepan Date: Mon, 20 Oct 2014 19:15:41 -0700 Subject: [PATCH] binary search code --- src/models/projects.coffee | 30 ++++++++++++++++++++++++++++-- src/utils/search.coffee | 23 +++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/utils/search.coffee diff --git a/src/models/projects.coffee b/src/models/projects.coffee index e967621..4231875 100644 --- a/src/models/projects.coffee +++ b/src/models/projects.coffee @@ -4,12 +4,16 @@ config = require '../models/config.coffee' mediator = require '../modules/mediator.coffee' Model = require '../utils/model.coffee' date = require '../utils/date.coffee' +search = require '../utils/search.coffee' user = require './user.coffee' module.exports = new Model 'name': 'models/projects' + 'data': + 'sortKey': 'priority' + find: (project) -> _.find @data.list, project @@ -32,6 +36,19 @@ module.exports = new Model clear: -> @set 'list', [] + # Sort an already sorted index. + sort: -> + # Get or initialize the index. + index = @data.index or [] + + for p in @data.list + for m in p.milestones + # Run a comparator here inserting into index. + @data.sortKey + + # Save the index. + @set 'index', index + onconstruct: -> mediator.on '!projects/add', _.bind @add, @ mediator.on '!projects/clear', _.bind @clear, @ @@ -40,7 +57,16 @@ module.exports = new Model # Init the projects. @set 'list', lscache.get('projects') or [] - # Persist projects in local storage (sans milestones). @observe 'list', (projects) -> + # Persist projects in local storage (sans milestones). lscache.set 'projects', _.pluckMany projects, [ 'owner', 'name' ] - , 'init': no \ No newline at end of file + # Update the index. + do @sort + , 'init': no + + # Reset our index and re-sort. + @observe 'sortKey', -> + # Use pop as Ractive is glitchy. + @pop 'index' while @data.index.length + # Run the sort again. + do @sort \ No newline at end of file diff --git a/src/utils/search.coffee b/src/utils/search.coffee new file mode 100644 index 0000000..e897972 --- /dev/null +++ b/src/utils/search.coffee @@ -0,0 +1,23 @@ +# Binary search implementation with a custom comparator function. +module.exports = (arr, item, comparator) -> + # Numeric comparator. + comparator ?= (a, b) -> + switch + when a < b then -1 + when a > b then +1 + else 0 + + minIndex = 0 + maxIndex = arr.length - 1 + + while minIndex <= maxIndex + index = (minIndex + maxIndex) / 2 | 0 + existing = arr[index] + + res = comparator existing, item + switch + when result < 0 then minIndex = index + 1 + when result > 0 then maxIndex = index - 1 + else return index + + -1 \ No newline at end of file