recursive-iterator
recursive-iterator copied to clipboard
current state not accessible
Hi, Could you add method to get the current state?
Current state is saved on this[STATE]
but I have no chance to get it back except doing this.__state
:(.
class RecursiveIterator {
...
getCurrentState() { return this[STATE]; }
...
}
Hi
What is use case for this?
I need to iterate over an object and to make promise
on leaf.
The result is a clone initial object with transformed leaf.
I've found this solution to iterate: (http://stackoverflow.com/questions/24660096/correct-way-to-write-loops-for-promise)
var promiseFor = Promise.method(function(condition, action, value) {
if (!condition(value)) return value;
return action(value).then(promiseFor.bind(null, condition, action));
});
with following implementation (i used your clone/copy implementation):
function transformObj(data) {
var rootNode = shallowCopy(data),
map = new Map(),
iterator = new RecursiveIterator(data, 1, true),
currentState;
map.set(data, rootNode);
return promiseFor(function(iterator) {
var state = iterator.next();
currentState = state.value;
return !state.done;
}, function(iterator) {
var parentNode = map.get(currentState.parent),
node = currentState.node;
return getNodePromiseValue(node, currentState.path, iterator)
.then(function(cleanNode) {
parentNode[currentState.key] = cleanNode;
map.set(node, cleanNode);
return iterator;
});
}, iterator)
.then(function() {
map.clear();
return rootNode;
});
}
getNodePromiseValue
is a function that return a promise.
But I need to store the current state currentState = state.value;
in the condition
function
It would be nice to have a getCurrentState
to make it simple like this:
function transformObj(data) {
var rootNode = shallowCopy(data),
map = new Map(),
iterator = new RecursiveIterator(data, 1, true);
map.set(data, rootNode);
return promiseFor(function(iterator) {
// I don't save current state here :)
return !iterator.next().done;
}, function(iterator) {
// I have iterator and it's current state :)
var currentState = iterator.getCurrentState(),
parentNode = map.get(currentState.parent),
node = currentState.node;
return getNodePromiseValue(node, currentState.path, iterator)
.then(function(cleanNode) {
parentNode[currentState.key] = cleanNode;
map.set(node, cleanNode);
return iterator;
});
}, iterator)
.then(function() {
map.clear();
return rootNode;
});
}
@amelon , thanks. Contribution is welcome (src + test).
@nervgh, do you accept I rename getState
to something like buildState
and I use getState
as the state getter ?
Could you add method to get the current state? https://github.com/nervgh/recursive-iterator/issues/3#issue-111152635
Please, add only the RecursiveIterator#getCurrentState()
method.
If you rename the RecursiveIterator#getState()
method then backward compatibility will be broken.