Skip to content

Commit

Permalink
Implement empty record / list optimisations.
Browse files Browse the repository at this point in the history
  • Loading branch information
Gozala committed Jul 10, 2015
1 parent cd13630 commit 300ac71
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 13 deletions.
26 changes: 19 additions & 7 deletions src/list.js
Original file line number Diff line number Diff line change
Expand Up @@ -77,29 +77,41 @@ class TypeInferedList extends BaseImmutableList {
const Type = this.constructor

if (input === null || input === void(0)) {
if (!Type[$empty]) {
if (!this[$empty]) {
const result = construct(this)
result[$store] = ImmutableList()
result.size = 0
Type[$empty] = result
this[$empty] = result
}

return Type[$empty]
return this[$empty]
}

if (input instanceof Type && input.constructor === Type) {
if (input instanceof Type && input && input.constructor === Type) {
return input
}


const list = this[$init]()
const source = Indexed(input)
const isEmpty = source.size === 0

if (isEmpty && this[$empty]) {
return this[$empty]
}


let list = this[$init]()
list.size = source.size
source.forEach((value, index) => {
list.set(index, value)
})

return this[$result](list)
list = this[$result](list)

if (isEmpty) {
this[$empty] = list
}

return list
}
[Typed.step](result, [key, value]) {
return change(result, (store=ImmutableList()) => store.set(key, value))
Expand Down
25 changes: 19 additions & 6 deletions src/record.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,19 +41,27 @@ class TypedRecord extends IterableKeyedBase {
return result.asImmutable()
}

[Typed.read](structure={}) {
[Typed.read](structure) {
const Type = this.constructor

if (structure instanceof Type && structure.constructor === Type) {
if (structure instanceof Type &&
structure &&
structure.constructor === Type) {
return structure
}

if (!structure || typeof(structure) !== "object") {
if (structure === null || (structure && typeof(structure) !== "object")) {
return TypeError(`Invalid data structure "${structure}" was passed to ${this[$typeName]()}`)
}

const seq = Seq(structure)
const type = this[$type]
const isEmpty = seq.size === 0


if (isEmpty && this[$empty]) {
return this[$empty]
}

let record
for (let key in type) {
Expand All @@ -68,7 +76,13 @@ class TypedRecord extends IterableKeyedBase {
record = this[$step](record || this[$init](), [key, result])
}

return this[$result](record)
record = this[$result](record)

if (isEmpty) {
this[$empty] = record
}

return record
}
[Typed.step](result, [key, value]) {
const store = result[$store] ? result[$store].set(key, value) :
Expand Down Expand Up @@ -118,9 +132,8 @@ class TypedRecord extends IterableKeyedBase {
return this
}

const RecordType = this.constructor
return this[$empty] ||
(RecordType[$empty] = new RecordType())
(this[$empty] = new this.constructor())
}

remove(key) {
Expand Down

0 comments on commit 300ac71

Please sign in to comment.