KoryNunn / unbox

get/set/etc into objs via an array of keys

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Your code may need simplifying

DFFZMXJ opened this issue · comments

I've checked out both your code and my code. It seems yours is too complicated.

My realizations:

//May be because it's recursive.
function get(reference, key){
    let indexes = typeof key==="string"?key.split('.'):key;
    let index = indexes.shift();
    if(indexes.length)
        return reference[index] instanceof Object?get(reference[index],indexes):undefined;
    else
        return reference[index];
}
//May be because I used ES6 features.
function set(reference, key, value){
    if(typeof key === "string")
        key = key.split('.');
    let finalKey = key.pop();
    let parentObject = reference;
    for(let index of key){
        if(!(parentObject[index] instanceof Object)||!(parentObject[index] instanceof Array))
            parentObject[index] = isNaN(index)?{}:[];
        parentObject = parentObject[index];
    }
    parentObject[finalKey] = value;
    return reference;
}

(My English sucks. Please do not care about it.) They're much simpler but they still work as yours.

By the way, thanks to you, I found the principle of function set.

Hi, thanks for the feedback, I found a bug in my set implementation while looking into this.

Your implementation does a few things the aren't great for performance, I've added some tests that demonstrate this: https://github.com/KoryNunn/unbox/blob/master/tests/index.js#L50

unbox implementation:

# get performance
ok 16 Took 398ms
# set performance
ok 17 Took 451ms

suggested implementation:

# get performance
ok 16 Took 536ms
# set performance
ok 17 Took 880ms