Skip to content

Commit

Permalink
Merge pull request #1601 from nunocastromartins/support-arrays-on-keys
Browse files Browse the repository at this point in the history
Add support for obs. arrays on `keys`. Fixes #1600
  • Loading branch information
mweststrate authored Aug 14, 2018
2 parents fe46d37 + 6d38609 commit 2d6cab7
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 @@ -15,6 +15,7 @@ import {
} from "../internal"

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 @@ -23,9 +24,12 @@ export function keys(obj: any): any {
if (isObservableMap(obj)) {
return Array.from(obj.keys())
}
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 @@ -224,6 +224,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 2d6cab7

Please sign in to comment.