Nodejs,redis自动完成器,闭包

时间:2014-01-22 17:27:40

标签: javascript node.js autocomplete

*代码重写

我正在尝试将antirez的autocompleter转换为javascript,以便与node.js一起使用。

我无法通过关闭问题。也许有人可以帮助我。

我看到问题所在,但无法弄清楚如何解决它们。

while循环正在触发,中断不正确且不起作用等。

代码:

var acp = {

  vars: {

    dict     : false,
    count    : false,
    prefix   : false,
    rangeLen : 10,
    start    : false,
    results  : false,
    range    : false,

  },

  sendResults: function(){
    console.log(acp.vars.results);
  },

  getzrank: function(){

    redis.zrank( acp.vars.dict, acp.vars.prefix, function( err, start ){

      acp.vars.start = start;

    });

  },

  getzrange: function(){

    redis.zrange( acp.vars.dict, acp.vars.start, parseFloat( acp.vars.start+acp.vars.rangeLen-1 ), function( err, range ){

      acp.vars.range = range;

    });

  },

  createAutocomplete: function(){

    while( acp.vars.results.length != acp.vars.count ){

      acp.getzrange();

      acp.vars.start+=acp.vars.rangeLen;

      if( ! acp.vars.range || acp.vars.range.length == 0 ) { break; }

      for ( var i in acp.vars.range ){

        var minLen =  Math.min(i.length,acp.vars.prefix.length); 

        if( i.substr( 0, minLen ) != acp.vars.prefix.substr( 0, minLen ) ){ 

          acp.vars.count = acp.vars.results.length;

        }

        if( i.substr( 0, i.length-1 ) == "*" && acp.vars.results.length != acp.vars.count) {

          acp.vars.results.push( i.substr(0,-1) );

        }

      }

    }

    acp.sendResults();

  },

  init: function(dict,prefix,count){

    acp.vars.range   = false;

    acp.vars.dict    = dict;
    acp.vars.prefix  = prefix;
    acp.vars.count   = count;
    acp.vars.results = [];

    acp.vars.start   = acp.getzrank();

    if( ! acp.vars.start ){ acp.sendResults(); }
    else{ acp.createAutocomplete(); }

  }

}

1 个答案:

答案 0 :(得分:0)

break语句超出了while循环的范围,因为它嵌套在匿名函数中。不确定是否能解决您的问题。