Quick actions

cmd+k|ctrl+k

Navigation

Languages

kv string to map

Snippet info

Language

JavaScript

Visibility

public

Author

pheker

Created

2018-05-07T14:09:33Z

Updated

2018-05-07T15:31:40Z

console.log("Hello World!");

function toMap(str){
    var ret = {}, len = 0;
    if(str === undefined || (len = str.length) === 0){
        return ret;
    }
    if(getType(str[0]) != 1) throw Error("字符串应以字母开头");
    var k = "",v = "";
    var hasK = false,hasV = false;
    for(var i=0; i<len; i++){
        var ch = str.charAt(i),type = getType(ch);
        if(type === 1){//letter
            if(!hasK) hasK = true;
            reset();
            k += ch;
        }else if(type === 2){
            if(!hasV) hasV = true;
            v += ch;
        }else throw Error("非法字符") 
    }
    if(!hasK || !hasV) throw Error("缺少key或value");
    reset();
    
    //  reset related state if find both k and v;
    function reset(cb){
        if(hasK && hasV){
            ret[k] = v;
            hasK = false;
            hasV = false;
            k = "";
            v = "";
        }
    }
    
    function getType(ch){
        if('a' <= ch && ch <= 'z') return 1;
        if('0' <= ch && ch <= '9') return 2;
        return 0;
    }
    return ret;
}

// test
console.time("ElapsedTime");
console.log(toMap("abcd1sdfs2xyz3"));
console.timeEnd("ElapsedTime");

// 非字母开头将会报错
// console.time("ElapsedTime");
// console.log(toMap("111abcd1sdfs2xyz3"));
// console.timeEnd("ElapsedTime");

INFO