gpt4 book ai didi

javascript - 工厂函数链表问题

转载 作者:行者123 更新时间:2023-12-02 14:22:08 25 4
gpt4 key购买 nike

我正在尝试使用工厂函数的方式来实现对象,并尝试使用链表示例,其中我初始化一个空链表,然后尝试添加节点,在添加方法方法中,我设置了头,如果它未设置,否则将该节点添加到链中的最后一个节点。 问题是头部似乎永远不会固定,有什么想法吗?

"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 类语法中的等效代码,它确实有效,(我听说工厂函数更好,因为它们避免了 new 和 this 关键字未正确设置的问题,这就是我尝试使用工厂函数的原因)

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
}
}
}
}
}

最佳答案

评论太长了。您似乎对 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
};

但实际上,在 JavaScript 中避免 this 是很困难的,你确实是在违背常规。另一方面,避免 new 非常简单,只需使用 Object.create 或对象文字即可。

关于javascript - 工厂函数链表问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38576565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com