Skip to content

refactor: linked-list find method refactor #18

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions src/linked-list/__tests__/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,25 @@ describe('LinkedList class', () => {
expect((findNode2 as Node).next).toBeDefined()
expect(((findNode2 as Node).next as Node).value).toBe(2)
})

it('should pass a compare function for finding target value', () => {
linkedList
.append(5)
.append({ key: 'stack', value: 'fizz' })
.append({ key: 123 })
.append(2)
.append(3)

const compare = (nodeValue: any): boolean => {
if (typeof nodeValue === 'object' && nodeValue.key) {
return nodeValue.key === 'stack'
} else {
return false
}
}

expect(linkedList.find('stack', compare))
})
})

describe('Method delete()', () => {
Expand Down
19 changes: 14 additions & 5 deletions src/linked-list/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,11 @@ export class LinkedList {
*/
public append(value: any): LinkedList {
this._length++

const newNode = new Node(value)

if (!this.head) {
this.head = newNode
this.tail = newNode

return this
}

Expand Down Expand Up @@ -68,13 +66,21 @@ export class LinkedList {
/**
* 根据value查找节点上第一个与value相等的节点,返回该节点或者null
* @param value 查找的值
* @param compare 查找函数
* @returns {INode|null} 找到的节点或者null
*/
public find(value: any): Node | null {
public find(value: any, compare?: (nodeValue: any) => boolean): Node | null {
let currentNode = this.head
while (currentNode !== null && currentNode.value !== value) {
currentNode = currentNode.next
if (compare) {
while (currentNode !== null && !compare(currentNode.value)) {
currentNode = currentNode.next
}
} else {
while (currentNode !== null && currentNode.value !== value) {
currentNode = currentNode.next
}
}

/** currentNode === null 时会跳出while,直接return */
return currentNode
}
Expand Down Expand Up @@ -258,6 +264,9 @@ export class LinkedList {
return this.head === null
}

/**
* 将链表转化成数组显示
*/
public toArray(): any[] {
const result = []
let currentNode = this.head
Expand Down