Skip to content

Commit 316150f

Browse files
authored
Simplify toJS() (immutable-js#1384)
This factors toJS() into its own function and simplifies the implementation to recurse within only toJS() instead of between toJS() and value.toJS(). Also, instead of sniffing for a .toJS function existing on the value, uses isImmutable() which consolidates this logic and makes it more predictable.
1 parent 5101b07 commit 316150f

File tree

3 files changed

+21
-8
lines changed

3 files changed

+21
-8
lines changed

src/CollectionImpl.js

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@ import deepEqual from './utils/deepEqual';
4848
import mixin from './utils/mixin';
4949
import quoteString from './utils/quoteString';
5050

51+
import { toJS } from './toJS';
5152
import { Map } from './Map';
5253
import { OrderedMap } from './OrderedMap';
5354
import { List } from './List';
@@ -118,9 +119,7 @@ mixin(Collection, {
118119
},
119120

120121
toJS() {
121-
return this.toSeq()
122-
.map(toJS)
123-
.toJSON();
122+
return toJS(this);
124123
},
125124

126125
toKeyedSeq() {
@@ -768,10 +767,6 @@ function entryMapper(v, k) {
768767
return [k, v];
769768
}
770769

771-
function toJS(value) {
772-
return value && typeof value.toJS === 'function' ? value.toJS() : value;
773-
}
774-
775770
function not(predicate) {
776771
return function() {
777772
return !predicate.apply(this, arguments);

src/Record.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
* LICENSE file in the root directory of this source tree.
66
*/
77

8+
import { toJS } from './toJS';
89
import { KeyedCollection } from './Collection';
910
import { keyedSeqFromValue } from './Seq';
1011
import { MapPrototype } from './Map';
@@ -144,7 +145,7 @@ export class Record {
144145
}
145146

146147
toJS() {
147-
return recordSeq(this).toJS();
148+
return toJS(this);
148149
}
149150

150151
__iterator(type, reverse) {

src/toJS.js

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* Copyright (c) 2014-present, Facebook, Inc.
3+
*
4+
* This source code is licensed under the MIT license found in the
5+
* LICENSE file in the root directory of this source tree.
6+
*/
7+
8+
import { Collection } from './Collection';
9+
import { isImmutable } from './Predicates';
10+
11+
export function toJS(value) {
12+
return isImmutable(value)
13+
? Collection(value)
14+
.map(toJS)
15+
.toJSON()
16+
: value;
17+
}

0 commit comments

Comments
 (0)