Skip to content
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

Generalize fromJS() and Seq() to support Sets #1865

Merged
merged 1 commit into from
Jul 23, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 15 additions & 0 deletions __tests__/Map.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,21 @@ describe('Map', () => {
expect(m.get('c')).toBe('C');
});

it('converts from JS (global) Map', () => {
const m = Map(
new global.Map([
['a', 'A'],
['b', 'B'],
['c', 'C'],
])
);
expect(Map.isMap(m)).toBe(true);
expect(m.size).toBe(3);
expect(m.get('a')).toBe('A');
expect(m.get('b')).toBe('B');
expect(m.get('c')).toBe('C');
});

it('constructor provides initial values', () => {
const m = Map({ a: 'A', b: 'B', c: 'C' });
expect(m.size).toBe(3);
Expand Down
21 changes: 20 additions & 1 deletion __tests__/Seq.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { isCollection, isIndexed, Seq } from 'immutable';
import { isCollection, isIndexed, isKeyed, Seq } from 'immutable';

describe('Seq', () => {
it('returns undefined if empty and first is called without default argument', () => {
Expand Down Expand Up @@ -73,6 +73,25 @@ describe('Seq', () => {
expect(empty.size).toEqual(0);
});

it('accepts a JS (global) Map', () => {
const seq = Seq(
new global.Map([
['a', 'A'],
['b', 'B'],
['c', 'C'],
])
);
expect(isKeyed(seq)).toBe(true);
expect(seq.size).toBe(3);
});

it('accepts a JS (global) Set', () => {
const seq = Seq(new global.Set(['a', 'b', 'c']));
expect(isIndexed(seq)).toBe(false);
expect(isKeyed(seq)).toBe(false);
expect(seq.size).toBe(3);
});

it('does not accept a scalar', () => {
expect(() => {
// @ts-expect-error
Expand Down
10 changes: 10 additions & 0 deletions __tests__/Set.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,16 @@ describe('Set', () => {
expect(s.has(2)).toBe(false);
});

it('accepts a JS (global) Set', () => {
const s = Set(new global.Set([1, 2, 3]));
expect(Set.isSet(s)).toBe(true);
expect(s.size).toBe(3);
expect(s.has(1)).toBe(true);
expect(s.has(2)).toBe(true);
expect(s.has(3)).toBe(true);
expect(s.has(4)).toBe(false);
});

it('accepts string, an array-like collection', () => {
const s = Set('abc');
expect(s.size).toBe(3);
Expand Down
59 changes: 58 additions & 1 deletion __tests__/fromJS.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,65 @@
import { runInNewContext } from 'vm';

import { isCollection, fromJS } from 'immutable';
import { List, Map, Set, isCollection, fromJS } from 'immutable';

describe('fromJS', () => {
it('convert Array to Immutable.List', () => {
const list = fromJS([1, 2, 3]);
expect(List.isList(list)).toBe(true);
expect(list.count()).toBe(3);
});

it('convert plain Object to Immutable.Map', () => {
const map = fromJS({ a: 'A', b: 'B', c: 'C' });
expect(Map.isMap(map)).toBe(true);
expect(map.count()).toBe(3);
});

it('convert JS (global) Set to Immutable.Set', () => {
const set = fromJS(new global.Set([1, 2, 3]));
expect(Set.isSet(set)).toBe(true);
expect(set.count()).toBe(3);
});

it('convert JS (global) Map to Immutable.Map', () => {
const map = fromJS(
new global.Map([
['a', 'A'],
['b', 'B'],
['c', 'C'],
])
);
expect(Map.isMap(map)).toBe(true);
expect(map.count()).toBe(3);
});

it('convert iterable to Immutable collection', () => {
function* values() {
yield 1;
yield 2;
yield 3;
}
const result = fromJS(values());
expect(List.isList(result)).toBe(true);
expect(result.count()).toBe(3);
});

it('does not convert existing Immutable collections', () => {
const orderedSet = Set(['a', 'b', 'c']);
expect(fromJS(orderedSet)).toBe(orderedSet);
});

it('does not convert strings', () => {
expect(fromJS('abc')).toBe('abc');
});

it('does not convert non-plain Objects', () => {
class Test {}
const result = fromJS(new Test());
expect(isCollection(result)).toBe(false);
expect(result instanceof Test).toBe(true);
});

it('is iterable outside of a vm', () => {
expect(isCollection(fromJS({}))).toBe(true);
});
Expand Down
10 changes: 10 additions & 0 deletions src/Iterator.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,13 @@ function getIteratorFn(iterable) {
return iteratorFn;
}
}

export function isEntriesIterable(maybeIterable) {
const iteratorFn = getIteratorFn(maybeIterable);
return iteratorFn && iteratorFn === maybeIterable.entries;
}

export function isKeysIterable(maybeIterable) {
const iteratorFn = getIteratorFn(maybeIterable);
return iteratorFn && iteratorFn === maybeIterable.keys;
}
14 changes: 8 additions & 6 deletions src/Seq.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {
hasIterator,
isIterator,
getIterator,
isEntriesIterable,
isKeysIterable,
} from './Iterator';

import hasOwnProperty from './utils/hasOwnProperty';
Expand Down Expand Up @@ -286,11 +288,7 @@ function emptySequence() {
}

export function keyedSeqFromValue(value) {
const seq = Array.isArray(value)
? new ArraySeq(value)
: hasIterator(value)
? new CollectionSeq(value)
: undefined;
const seq = maybeIndexedSeqFromValue(value);
if (seq) {
return seq.fromEntrySeq();
}
Expand All @@ -316,7 +314,11 @@ export function indexedSeqFromValue(value) {
function seqFromValue(value) {
const seq = maybeIndexedSeqFromValue(value);
if (seq) {
return seq;
return isEntriesIterable(value)
? seq.fromEntrySeq()
: isKeysIterable(value)
? seq.toSetSeq()
: seq;
}
if (typeof value === 'object') {
return new ObjectSeq(value);
Expand Down
22 changes: 13 additions & 9 deletions src/fromJS.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import { KeyedSeq, IndexedSeq } from './Seq';
import { Seq } from './Seq';
import { hasIterator } from './Iterator';
import { isImmutable } from './predicates/isImmutable';
import { isIndexed } from './predicates/isIndexed';
import { isKeyed } from './predicates/isKeyed';
import isArrayLike from './utils/isArrayLike';
import isPlainObj from './utils/isPlainObj';

export function fromJS(value, converter) {
Expand All @@ -14,12 +18,11 @@ export function fromJS(value, converter) {
}

function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
const toSeq = Array.isArray(value)
? IndexedSeq
: isPlainObj(value)
? KeyedSeq
: null;
if (toSeq) {
if (
typeof value !== 'string' &&
!isImmutable(value) &&
(isArrayLike(value) || hasIterator(value) || isPlainObj(value))
) {
if (~stack.indexOf(value)) {
throw new TypeError('Cannot convert circular structure to Immutable');
}
Expand All @@ -28,7 +31,7 @@ function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
const converted = converter.call(
parentValue,
key,
toSeq(value).map((v, k) =>
Seq(value).map((v, k) =>
fromJSWith(stack, converter, v, k, keyPath, value)
),
keyPath && keyPath.slice()
Expand All @@ -41,5 +44,6 @@ function fromJSWith(stack, converter, value, key, keyPath, parentValue) {
}

function defaultConverter(k, v) {
return isKeyed(v) ? v.toMap() : v.toList();
// Effectively the opposite of "Collection.toSeq()"
return isIndexed(v) ? v.toList() : isKeyed(v) ? v.toMap() : v.toSet();
}
12 changes: 8 additions & 4 deletions type-definitions/immutable.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4871,6 +4871,10 @@ declare namespace Immutable {
/**
* Deeply converts plain JS objects and arrays to Immutable Maps and Lists.
*
* `fromJS` will convert Arrays and [array-like objects][2] to a List, and
* plain objects (without a custom prototype) to a Map. [Iterable objects][3]
* may be converted to List, Map, or Set.
*
* If a `reviver` is optionally provided, it will be called with every
* collection as a Seq (beginning with the most nested collections
* and proceeding to the top-level collection itself), along with the key
Expand All @@ -4893,10 +4897,6 @@ declare namespace Immutable {
* }
* ```
*
* `fromJS` is conservative in its conversion. It will only convert
* arrays which pass `Array.isArray` to Lists, and only raw objects (no custom
* prototype) to Map.
*
* Accordingly, this example converts native JS data to OrderedMap and List:
*
* <!-- runkit:activate -->
Expand Down Expand Up @@ -4933,6 +4933,10 @@ declare namespace Immutable {
*
* [1]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Example.3A_Using_the_reviver_parameter
* "Using the reviver parameter"
* [2]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Indexed_collections#working_with_array-like_objects
* "Working with array-like objects"
* [3]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#the_iterable_protocol
* "The iterable protocol"
*/
function fromJS(
jsValue: unknown,
Expand Down