immutable-treeUtils樹的理解

一、node

function TreeUtils(
rootPath,
idKey,
childNodesKey,
none
) {
this.rootPath = rootPath || Seq()
this.idKey = idKey || 'id'
this.childNodesKey =
childNodesKey || 'childNodes'
this.none =
typeof none !== 'undefined'
? none
: NONE
}ide

建立一個樹,參數分別是一個數據類型爲seq()的根路徑,id,childNodesKey(數據中的一個子數據集)this

 

二、獲取全部state數據中的childprototype

TreeUtils.prototype.nodes = function(
state,
path
) {
var childNodesKey = this.childNodesKey
var result = List()
var stack = List.of(
path || this.rootPath
)
while (stack.size > 0) {
var keyPath = stack.first()
result = result.push(keyPath)get

stack = stack.shift()string

var item = state.getIn(keyPath)
var childNodes = item.get(
childNodesKey
)
if (
childNodes &&
childNodes.size > 0
) {
item
.get(childNodesKey)
.keySeq()
.forEach(function(i) {
stack = stack.push(
keyPath.concat(
childNodesKey,
i
)
)
})
}
}it

return result
}io

 

三、根據id獲取childtable

/**
* @id TreeUtils-byId
* @lookup byId
*
* #### *method* byId()
*
* Returns the key path to the node with id === `id`.
*
* ###### Signature:
* ```js
* id(
* state: Immutable.Iterable,
* id: string
* ): Immutable.Seq<string|number>
* ```
*
* ###### Arguments:
* * `id` - A unique identifier
*
* ###### Returns:
* The key path to the node with id === `id`.
*/
TreeUtils.prototype.byId = function(
state,
id
) {
var idKey = this.idKey
return this.find(state, function(
item
) {
return item.get(idKey) === id
})
}function

 

四、find查找,會調用treeUtils.nodes獲取全部的child,從child中獲取符合條件的child

/** * @id TreeUtils-find * @lookup find * * #### *method* find() * * Returns the key path to the first node for which `compatator` returns `true`. Uses >nodes internally and as >nodes is an **unordered** List, you should probably use this to find unique occurences of data. * ```js * treeUtils.find(state, node => node.get('name') === 'Me in Paris'); * // Seq ["childNodes", 0, "childNodes", 0] * ``` * * ###### Signature: * ```js * find( * state: Immutable.Iterable, * comparator: ( * node: Immutable.Iterable, * keyPath: Immutable.Seq<string|number> * ): boolean, * path?: Immutable.Seq<string|number> * ): Immutable.Seq<string|number> * ``` * * ###### Arguments: * * `comparator` - A function that gets passed a `node` and its `keyPath` and should return whether it fits the criteria or not. * * `path?` - An optional key path to the (sub)state you want to analyse: Default: The `TreeUtils` object's `rootPath`. * * ###### Returns: * The key path to the first node for which `comparator` returned `true`. */TreeUtils.prototype.find = function( state, comparator, path) { return this.nodes(state, path).find( function(keyPath) { return ( comparator( state.getIn(keyPath), keyPath ) === true ) }, this, this.none )}

相關文章
相關標籤/搜索