Skip to content

Commit

Permalink
Add support for obs. arrays on keys. Fixes #1600
Browse files Browse the repository at this point in the history
  • Loading branch information
YarnSphere authored and mweststrate committed Aug 21, 2018
1 parent a9b87b8 commit 1b2d4e0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
6 changes: 5 additions & 1 deletion src/api/object-api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { getAdministration } from "../types/type-utils"
import { ObservableValue } from "../types/observablevalue"

export function keys<K>(map: ObservableMap<K, any>): ReadonlyArray<K>
export function keys<T>(ar: IObservableArray<T>): ReadonlyArray<number>
export function keys<T extends Object>(obj: T): ReadonlyArray<string>
export function keys(obj: any): any {
if (isObservableObject(obj)) {
Expand All @@ -20,9 +21,12 @@ export function keys(obj: any): any {
if (isObservableMap(obj)) {
return (obj as any)._keys.slice()
}
if (isObservableArray(obj)) {
return obj.map((_, index) => index)
}
return fail(
process.env.NODE_ENV !== "production" &&
"'keys()' can only be used on observable objects and maps"
"'keys()' can only be used on observable objects, arrays and maps"
)
}

Expand Down
16 changes: 16 additions & 0 deletions test/base/object-api.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,22 @@ test("array - set, remove, entries are reactive", () => {
])
})

test("array - set, remove, keys are reactive", () => {
const todos = observable.array()
const snapshots = []

reaction(() => keys(todos), keys => snapshots.push(keys))

set(todos, 0, 2)
set(todos, "1", 4)
set(todos, 3, 4)
set(todos, 1, 3)
remove(todos, 2)
remove(todos, "0")

expect(snapshots).toEqual([[0], [0, 1], [0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2], [0, 1]])
})

test("observe & intercept", () => {
let events = []
const todos = observable(
Expand Down

0 comments on commit 1b2d4e0

Please sign in to comment.