Skip to content

Incorrect test in __rest helper for Object rest #12227

Closed
@rbuckton

Description

@rbuckton

TypeScript Version: 2.2.0-dev.20161114
The emit for __rest uses !e.indexOf(p) to check as to whether a property name should be excluded. This test is incorrect as Array.prototype.indexOf return -1 if an element is not found, or a zero-bounded index if an element is found, for example:

const e = ["a", "b"];
!e.indexOf("a") === !(0)  === true  // fail, we want 'false' here`
!e.indexOf("b") === !(1)  === false // ok, we want 'false' here`
!e.indexOf("c") === !(-1) === false // fail, we want 'true' here`

A concise and correct test should instead be !~e.indexOf(p), as unary ~ will give the twos-complement of e.indexOf(p):

const e = ["a", "b"];
!~e.indexOf("a") === !~(0)  === !(-1) === false // ok, we want 'false' here
!~e.indexOf("b") === !~(1)  === !(-2) === false // ok, we want 'false' here
!~e.indexOf("c") === !~(-1) === !(0)  === true  // ok, we want 'true' here

Expected emit:

var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && !~e.indexOf(p))
        t[p] = s[p];
    return t;
};

Actual emit:

var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && !e.indexOf(p))
        t[p] = s[p];
    return t;
};

Metadata

Metadata

Assignees

Labels

BugA bug in TypeScriptFixedA PR has been merged for this issue

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions