From 72161a64b2c3637d9b204d4841ac669f547fd4f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gr=C3=A9goire=20Geis?= Date: Wed, 27 Mar 2019 08:58:38 +0900 Subject: [PATCH] @babel/traverse: Fix NodePath.getData (#9415) * @babel/traverse: Fix NodePath.getData Currently, if the obtained value is `false`, it will be replaced by the given default value, which is invalid. This makes sure that we only set the default value when the value is `undefined`, instead of falsy. * Add test and fix object protoype * Allow false as default value --- packages/babel-traverse/src/path/index.js | 4 +- packages/babel-traverse/test/path/index.js | 43 ++++++++++++++++++++++ 2 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 packages/babel-traverse/test/path/index.js diff --git a/packages/babel-traverse/src/path/index.js b/packages/babel-traverse/src/path/index.js index f76ba1ec5ece..a1be4f5d8d00 100644 --- a/packages/babel-traverse/src/path/index.js +++ b/packages/babel-traverse/src/path/index.js @@ -28,7 +28,7 @@ export default class NodePath { this.parent = parent; this.hub = hub; this.contexts = []; - this.data = {}; + this.data = Object.create(null); this.shouldSkip = false; this.shouldStop = false; this.removed = false; @@ -116,7 +116,7 @@ export default class NodePath { getData(key: string, def?: any): any { let val = this.data[key]; - if (!val && def) val = this.data[key] = def; + if (val === undefined && def !== undefined) val = this.data[key] = def; return val; } diff --git a/packages/babel-traverse/test/path/index.js b/packages/babel-traverse/test/path/index.js new file mode 100644 index 000000000000..5758a13cf838 --- /dev/null +++ b/packages/babel-traverse/test/path/index.js @@ -0,0 +1,43 @@ +import { NodePath } from "../../lib"; + +describe("NodePath", () => { + describe("setData/getData", () => { + it("can set default value", () => { + const path = new NodePath({}, {}); + + expect(path.getData("foo", "test")).toBe("test"); + }); + it("can set false", () => { + const path = new NodePath({}, {}); + path.setData("foo", false); + + expect(path.getData("foo", true)).toBe(false); + }); + + it("can set true", () => { + const path = new NodePath({}, {}); + path.setData("foo", true); + + expect(path.getData("foo", false)).toBe(true); + }); + + it("can set null", () => { + const path = new NodePath({}, {}); + path.setData("foo", null); + + expect(path.getData("foo", true)).toBe(null); + }); + + it("can use false as default", () => { + const path = new NodePath({}, {}); + + expect(path.getData("foo", false)).toBe(false); + }); + + it("does not use object base properties", () => { + const path = new NodePath({}, {}); + + expect(path.getData("__proto__", "test")).toBe("test"); + }); + }); +});