2016-07-25 28 views
0

我想使用工厂函数的方式来实现一个对象,并试图与链接列表示例,其中我初始化一个空的链接列表,然后尝试添加节点,在添加方法方法I如果未设置,则设置头部,否则将该节点添加到链中的最后一个节点。 问题是,头从来没有出现设置,任何想法为什么?工厂函数链表问题

"use strict" 

const niceLog = s => { 
    console.log(JSON.stringify(s, null, 2)) 
} 

function linkedList() { 
    let head 

    const node = data => { 
    return { 
     data, 
     next: null 
    } 
    } 

    const add = data => { 
    if (!head) { 
     head = node(data) 
    } else { 
     const end = node(data) 
     let n = head 
     while (n.next) n = n.next 
     n.next = end 
    } 
    } 

    const del = data => { 
    let n = head 

    if (n.data === data) head = head.next 

    while (n.next) { 
     if (n.next.data === data) { 
     n.next = n.next.next 
     return 
     } 
     n = n.next 
    } 
    } 


    return { 
    head, 
    add, 
    del 
    } 
} 


const ll = linkedList() 

ll.add('cheese') 
ll.add('crackers') 
ll.add('tea') 
ll.add('coffee') 

niceLog(ll) // {} 

这里是ES6类语法等效代码不工作,(我曾听说工厂功能更好,因为它们避免新的问题和这个关键词没有被正确设定这就是为什么我试图使用工厂功能)

const niceLog = s => { 
    console.log(JSON.stringify(s, null, 2)) 
} 

class Node { 
    constructor(data) { 
    this.data = data 
    this.next = null 
    } 
} 

class LinkedList { 
    constructor() { 
    this.head = null 
    } 

    add(data){ 
    if (!this.head) { 
     this.head = new Node(data) 
    } else { 
     const end = new Node(data) 
     let n = this.head 
     while (n.next) n = n.next 
     n.next = end 
    } 
    } 

    del(data) { 
    let n = this.head 

    if (n.data === data) this.head = this.head.next 

    while (n.next) { 
     if (n.next.data === data) { 
     n.next = n.next.next 
     return 
     } 
     n = n.next 
    } 
    } 
} 


const ll = new LinkedList() 

ll.add('cheese') 
ll.add('crackers') 
ll.add('tea') 
ll.add('coffee') 

niceLog(ll) // output = 


"head": { 
    "data": "cheese", 
    "next": { 
     "data": "crackers", 
     "next": { 
     "data": "tea", 
     "next": { 
      "data": "coffee", 
      "next": null 
     } 
     } 
    } 
    } 
} 
+2

所以...你的问题是什么? –

+0

我现在添加了问题部分! – Heisenberg

回答

2

这是太长的评论。您似乎对JavaScript中的“工厂函数”是什么感到困惑。工厂功能不是表示您避免使用this关键字。这意味着你避免new关键字:

let myFactoryPrototype = { 
    someMethod: function() { 
    return this.foo; 
    } 
}; 

let myFactory =() => Object.create(myFactoryPrototype); 
let myObject = myFactory(); // no 'new' 

注意定期和箭头函数语法的组合。我已经使用了箭头功能,其中this无关紧要,并且使用了常规的旧function。如果你想避免this那么就不要使用方法,使用的数据类型进行操作规则(可能是纯)功能:

const addToLinkedList = (list, node) => { 
    // code return a new list with the extra node goes here 
}; 

不过说真的,避免this很难在JavaScript中,你真的削减对粮食。另一方面避免new是相当容易的,只需使用Object.create或对象文字。