Skip to content

Commit

Permalink
fix(SymbolShim): ensure for function even if Symbol already exists
Browse files Browse the repository at this point in the history
In some engines, Symbol exists but does not impelment the for method.

fixes #999
  • Loading branch information
benlesh committed Dec 8, 2015
1 parent 1298b57 commit e942776
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 12 deletions.
28 changes: 19 additions & 9 deletions spec/util/SymbolShim-spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,18 @@ describe('SymbolShim', function () {
expect(test).toBe('@@test');
});

it('should add a for method even if Symbol already exists but does not have for', function () {
var root = {
Symbol: {}
};
var result = polyfillSymbol(root);

expect(typeof result.for).toBe('function');

var test = result.for('test');
expect(test).toBe('@@test');
});

describe('when symbols exists on root', function () {
it('should use symbols from root', function () {
var root = {
Expand Down Expand Up @@ -59,17 +71,15 @@ describe('SymbolShim', function () {
expect(result.observable).toBe('@@observable');
});
});
});

describe('ensureIterator', function () {
it('should patch root using for symbol if exist', function () {
it('should patch root using Symbol.for if exist', function () {
var root = {
Symbol: {
for: function (x) { return x; }
}
};
ensureIterator(root.Symbol, root);
expect(root.Symbol.iterator).toBe(root.Symbol.for('iterator'));
var result = polyfillSymbol(root);
expect(result.iterator).toBe(root.Symbol.for('iterator'));
});

it('should patch using Set for mozilla bug', function () {
Expand All @@ -82,8 +92,8 @@ describe('ensureIterator', function () {
Symbol: {}
};

ensureIterator(root.Symbol, root);
expect(root.Symbol.iterator).toBe('@@iterator');
var result = polyfillSymbol(root);
expect(result.iterator).toBe('@@iterator');
});

it('should patch using map for es6-shim', function () {
Expand All @@ -95,7 +105,7 @@ describe('ensureIterator', function () {
root.Map.prototype.key = 'iteratorValue';
root.Map.prototype.entries = 'iteratorValue';

ensureIterator(root.Symbol, root);
expect(root.Symbol.iterator).toBe('key');
var result = polyfillSymbol(root);
expect(result.iterator).toBe('key');
});
});
11 changes: 8 additions & 3 deletions src/util/SymbolShim.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ export function polyfillSymbol(root) {
const Symbol = ensureSymbol(root);
ensureIterator(Symbol, root);
ensureObservable(Symbol);
ensureFor(Symbol);
return Symbol;
}

export function ensureFor(Symbol) {
if (!Symbol.for) {
Symbol.for = symbolForPolyfill;
}
}

export function ensureSymbol(root) {
if (!root.Symbol) {
root.Symbol = {
for: symbolForPolyfill
};
root.Symbol = {};
}
return root.Symbol;
}
Expand Down

0 comments on commit e942776

Please sign in to comment.