javascript - Describing Binary Tree with ImmutableJS & custom setIn function -
i trying immutable tree structure in light of immutable-js. people/exemple saw using either map or list immutable structure, feels cheating, , not having classic tree structure. wondering best way adapt classic tree make immutable. in case asking why, need tree immutable in order fluxjs store work fine. , no, changing flux lib not possible solution ;)
so here little classes have written in order describe tree.
export default class parsetree { constructor ( ) { this.root = null } setin( pathtonodetomodify, newvalue ) { //code here } } export class leaf { constructor( value ) { this.data = value; this.children = null; } } export class node { constructor( isparallel, children = [] ) { this.data = map( { id : createuniqueid(), isparallel : isparallel }); this.children = children; } }
question 1 - how feel way of building tree ?
as can see, working on setin function, in light of 1 immutablejs map have ( parameters : path node, new value). managed cheat ( @ least coding feels like... feel terrible) , make addtotree function :
addtotree( process ) { let state = this.getstate(); var root = state.root; if ( !root ) { state = object.create( parsetree.prototype) state.root= new leaf( process ); return state; } let oldstate = state; //creating parsetree newnode var newnode = object.create( parsetree.prototype) newnode.root = object.create( leaf.prototype); newnode.root.data = process; newnode.root.children = null; // creating new parsetree composed of oldparsetree , newnode-parsetree state = object.create( parsetree.prototype) state.root= object.create( node.prototype); state.root.data = map( {isparallel : true, id : createuniqueid()}); //for later: need adapt position/location of process state.root.children = [ oldstate, newnode ]; return state; }
following immutable-js code looked @ on github, tried getting function find path specific node following predicate ( suppose return 1 , 1 node, predicate on ids.) decided return list of ids, return list of indexes.
findpathto ( tree, predicate, keypath = list() ) { const root = tree.root; if ( root != null ) { if ( this.isleaf(root) ) { if ( predicate(root) ) { keypath = keypath.push(root.data.get('id')); } } else { keypath = keypath.push(root.data.get('id')); root.children.foreach( (onechild) => { keypath = this.findpathto( onechild , predicate, keypath ); }); } return keypath; } throw new typeerror( 'invalid tree : tree empty. try building process.' ) }
question 2 - using findpathto function , having newvalue set fluxjs, confused on how should implement setin function , keep state of store ( tree) immutable.
wiki
Comments
Post a Comment