krl-stdlib
Advanced tools
Comparing version 0.7.3 to 0.7.4
{ | ||
"name": "krl-stdlib", | ||
"version": "0.7.3", | ||
"version": "0.7.4", | ||
"description": "Standard library for KRL", | ||
@@ -5,0 +5,0 @@ "main": "src/index.js", |
@@ -524,2 +524,5 @@ var _ = require("lodash"); | ||
stdlib.put = function(ctx, val, path, to_set){ | ||
if(!_.isObject(val)){//if not Map or Array | ||
return val; | ||
} | ||
if(arguments.length < 3){ | ||
@@ -536,10 +539,24 @@ return val; | ||
} | ||
//TODO optimize | ||
var n_val = _.cloneDeep(val); | ||
_.update(n_val, path, function(at_p){ | ||
if(_.isPlainObject(to_set)){ | ||
return _.assign(at_p, to_set); | ||
var nested = n_val; | ||
var i, key; | ||
for(i = 0; i < path.length; i++){ | ||
key = path[i]; | ||
if(i === path.length - 1){ | ||
if(_.isObject(to_set)){ | ||
//merge onto the current Map or Array | ||
nested[key] = _.assign({}, nested[key], to_set); | ||
}else{ | ||
nested[key] = to_set; | ||
} | ||
}else{ | ||
if(_.isObject(nested[key])){//if Map or Array | ||
//simply traverse down | ||
}else{ | ||
//need to create a Map to continue | ||
nested[key] = {}; | ||
} | ||
nested = nested[key]; | ||
} | ||
return to_set; | ||
}); | ||
} | ||
return n_val; | ||
@@ -546,0 +563,0 @@ }; |
@@ -476,2 +476,27 @@ var _ = require("lodash"); | ||
tf("put", [5, ["key"], 9], 5, "if val is not a Map or Array, return the val"); | ||
tf("put", ["wat", ["key"], 9], "wat", "if val is not a Map or Array, return the val"); | ||
tf("put", [null, ["key"], 9], null, "if val is not a Map or Array, return the val"); | ||
t.equals( | ||
JSON.stringify(stdlib["put"](defaultCTX, {}, ["0", "0"], "foo")), | ||
"{\"0\":{\"0\":\"foo\"}}", | ||
"don't use arrays by default, i.e. don't do {\"0\":[\"foo\"]}" | ||
); | ||
t.equals( | ||
JSON.stringify(stdlib["put"](defaultCTX, {}, [0, 1], "foo")), | ||
"{\"0\":{\"1\":\"foo\"}}", | ||
"don't do {\"0\":[null,\"foo\"]}" | ||
); | ||
t.equals( | ||
JSON.stringify(stdlib["put"](defaultCTX, [], [0, 0], "foo")), | ||
"[{\"0\":\"foo\"}]" | ||
); | ||
t.equals( | ||
JSON.stringify(stdlib["put"](defaultCTX, [["wat?"]], [0, 0], "foo")), | ||
"[[\"foo\"]]", | ||
"if the nested value is an array, keep it an array" | ||
); | ||
tf("get", [obj, ["foo", "bar", "10"]], "I like cheese"); | ||
@@ -478,0 +503,0 @@ tf("get", [obj, "colors"], "many"); |
97444
1146