Prefer const wherever possible

Summary:
Non-final identifiers make code harder to understand.
This is particularly true for JavaScript where even the *type*
can change as a value gets reassigned later.

This enforces to use `const` whereever possible, but doesn't
"outlaw" `let`. Mixed destructuring is also still allowed.

Used `eslint --fix` to change all existing cases.

Reviewed By: jknoxville

Differential Revision: D16131329

fbshipit-source-id: 2eceaca7c603b71b36e005be5d135e1849f2518d
This commit is contained in:
Pascal Hartig
2019-07-09 04:15:32 -07:00
committed by Facebook Github Bot
parent 662db20948
commit c588b650ae
34 changed files with 141 additions and 140 deletions

View File

@@ -49,7 +49,7 @@ export default class TemperatureTable extends Component<TemperatureTableProps> {
};
buildRows = () => {
let rows = [];
const rows = [];
for (const tz of Object.keys(this.props.temperatureMap).sort()) {
rows.push(this.buildRow(tz, this.props.temperatureMap[tz]));
}

View File

@@ -6,7 +6,7 @@
*/
import {FlipperDevicePlugin, Device} from 'flipper';
let adb = require('adbkit-fb');
const adb = require('adbkit-fb');
import TemperatureTable from './TemperatureTable.js';
import {
@@ -107,7 +107,7 @@ const Heading = styled('div')({
// check if str is a number
function isNormalInteger(str) {
let n = Math.floor(Number(str));
const n = Math.floor(Number(str));
return String(n) === str && n >= 0;
}
@@ -145,7 +145,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
}
init() {
let device = ((this.device: any): AndroidDevice);
const device = ((this.device: any): AndroidDevice);
this.adbClient = device.adb;
this.updateHardwareInfo();
@@ -153,9 +153,9 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
// check how many cores we have on this device
this.executeShell((output: string) => {
let idx = output.indexOf('-');
let cpuFreq = [];
let count = parseInt(output.substring(idx + 1), 10) + 1;
const idx = output.indexOf('-');
const cpuFreq = [];
const count = parseInt(output.substring(idx + 1), 10) + 1;
for (let i = 0; i < count; ++i) {
cpuFreq[i] = {
cpu_id: i,
@@ -187,8 +187,8 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateCoreFrequency = (core: number, type: string) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
let newFreq = isNormalInteger(output) ? parseInt(output, 10) : -1;
const cpuFreq = this.state.cpuFreq;
const newFreq = isNormalInteger(output) ? parseInt(output, 10) : -1;
// update table only if frequency changed
if (cpuFreq[core][type] != newFreq) {
@@ -207,12 +207,12 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateAvailableFrequencies = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
let freqs = output.split(' ').map((num: string) => {
const cpuFreq = this.state.cpuFreq;
const freqs = output.split(' ').map((num: string) => {
return parseInt(num, 10);
});
cpuFreq[core].scaling_available_freqs = freqs;
let maxFreq = cpuFreq[core].scaling_max_freq;
const maxFreq = cpuFreq[core].scaling_max_freq;
if (maxFreq > 0 && freqs.indexOf(maxFreq) == -1) {
freqs.push(maxFreq); // always add scaling max to available frequencies
}
@@ -224,7 +224,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
updateCoreGovernor = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
if (output.toLowerCase().includes('no such file')) {
cpuFreq[core].scaling_governor = 'N/A';
} else {
@@ -238,7 +238,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
readAvailableGovernors = (core: number) => {
this.executeShell((output: string) => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
cpuFreq[core].scaling_available_governors = output.split(' ');
this.setState({
@@ -248,7 +248,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
readCoreFrequency = (core: number) => {
let freq = this.state.cpuFreq[core];
const freq = this.state.cpuFreq[core];
if (freq.cpuinfo_max_freq < 0) {
this.updateCoreFrequency(core, 'cpuinfo_max_freq');
}
@@ -296,21 +296,21 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
readThermalZones = () => {
let thermal_dir = '/sys/class/thermal/';
let map = {};
const thermal_dir = '/sys/class/thermal/';
const map = {};
this.executeShell(async (output: string) => {
if (output.toLowerCase().includes('permission denied')) {
this.setState({thermalAccessible: false});
return;
}
let dirs = output.split(/\s/);
let promises = [];
const dirs = output.split(/\s/);
const promises = [];
for (let d of dirs) {
d = d.trim();
if (d.length == 0) {
continue;
}
let path = thermal_dir + d;
const path = thermal_dir + d;
promises.push(this.readThermalZone(path, d, map));
}
await Promise.all(promises);
@@ -374,7 +374,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
cleanup = () => {
let cpuFreq = this.state.cpuFreq;
const cpuFreq = this.state.cpuFreq;
for (let i = 0; i < this.state.cpuCount; ++i) {
cpuFreq[i].scaling_cur_freq = -1;
cpuFreq[i].scaling_min_freq = -1;
@@ -394,7 +394,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
};
buildRow = (freq: CPUFrequency, idx: number) => {
let selected = this.state.selectedIds.indexOf(idx) >= 0;
const selected = this.state.selectedIds.indexOf(idx) >= 0;
let style = {};
if (freq.scaling_cur_freq == -2) {
style = {
@@ -466,11 +466,11 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
if (freq.scaling_available_freqs.length == 0) {
return <Text>N/A</Text>;
}
let info = freq;
const info = freq;
return (
<Text>
{freq.scaling_available_freqs.map((freq, idx) => {
let style = {};
const style = {};
if (
freq == info.scaling_cur_freq ||
freq == info.scaling_min_freq ||
@@ -519,15 +519,15 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
sidebarRows = (id: number) => {
let availableFreqTitle = 'Scaling Available Frequencies';
let selected = this.state.cpuFreq[id];
const selected = this.state.cpuFreq[id];
if (selected.scaling_available_freqs.length > 0) {
availableFreqTitle +=
' (' + selected.scaling_available_freqs.length.toString() + ')';
}
let keys = [availableFreqTitle, 'Scaling Available Governors'];
const keys = [availableFreqTitle, 'Scaling Available Governors'];
let vals = [
const vals = [
this.buildAvailableFreqList(selected),
this.buildAvailableGovList(selected),
];
@@ -540,8 +540,8 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
if (!this.state.displayCPUDetail || this.state.selectedIds.length == 0) {
return null;
}
let id = this.state.selectedIds[0];
let cols = {
const id = this.state.selectedIds[0];
const cols = {
key: {
value: 'key',
resizable: true,
@@ -551,7 +551,7 @@ export default class CPUFrequencyTable extends FlipperDevicePlugin<CPUState> {
resizable: true,
},
};
let colSizes = {
const colSizes = {
key: '35%',
value: 'flex',
};

View File

@@ -346,20 +346,20 @@ test('test parsing of path when a regex is not present', () => {
});
test('test shouldShowCrashNotification function for all correct inputs', () => {
const device = new BaseDevice('TH1S-15DEV1CE-1D', 'emulator', 'test device');
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-15DEV1CE-1D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(device, content);
expect(shouldShowNotification).toEqual(true);
});
test('test shouldShowCrashNotification function for all correct inputs but incorrect id', () => {
const device = new BaseDevice('TH1S-15DEV1CE-1D', 'emulator', 'test device');
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-1598DEV1CE-2D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(device, content);
expect(shouldShowNotification).toEqual(false);
});
test('test shouldShowCrashNotification function for undefined device', () => {
let content =
const content =
'Blaa Blaaa \n Blaa Blaaa \n Path: path/to/simulator/TH1S-1598DEV1CE-2D/App Name.app/App Name \n Blaa Blaa \n Blaa Blaa';
const shouldShowNotification = shouldShowCrashNotification(null, content);
expect(shouldShowNotification).toEqual(false);

View File

@@ -544,7 +544,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
};
static trimCallStackIfPossible = (callstack: string): string => {
let regex = /Application Specific Information:/;
const regex = /Application Specific Information:/;
const query = regex.exec(callstack);
return query ? callstack.substring(0, query.index) : callstack;
};
@@ -555,7 +555,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
persistedState: PersistedState,
): Array<Notification> => {
const filteredCrashes = persistedState.crashes.filter(crash => {
let ignore = !crash.name && !crash.reason;
const ignore = !crash.name && !crash.reason;
if (ignore) {
console.error('Ignored the notification for the crash', crash);
}
@@ -563,7 +563,7 @@ export default class CrashReporterPlugin extends FlipperDevicePlugin<
});
return filteredCrashes.map((crash: Crash) => {
const id = crash.notificationID;
let name: string = crash.name || crash.reason;
const name: string = crash.name || crash.reason;
let title: string = 'CRASH: ' + truncate(name, 50);
title = `${
name == crash.reason

View File

@@ -302,7 +302,7 @@ export default class extends FlipperPlugin<PluginState, *, PersistedState> {
this.props.setPersistedState({imagesMap: images}),
);
let images = this.filterImages(
const images = this.filterImages(
this.props.persistedState.images,
this.props.persistedState.events,
this.state.selectedSurface,

View File

@@ -28,7 +28,7 @@ function constructSearchResultTree(
AXMode: boolean,
AXNode: ?Element,
): SearchResultTree {
let searchResult = {
const searchResult = {
id: node.id,
isMatch,
hasChildren: children.length > 0,
@@ -118,7 +118,7 @@ class ProxyArchiveClient {
}
const {ids} = paramaters;
const arr: Array<Element> = [];
for (let id: ElementID of ids) {
for (const id: ElementID of ids) {
arr.push(this.persistedState.elements[id]);
}
return Promise.resolve({elements: arr});
@@ -129,7 +129,7 @@ class ProxyArchiveClient {
}
const {ids} = paramaters;
const arr: Array<Element> = [];
for (let id: ElementID of ids) {
for (const id: ElementID of ids) {
arr.push(this.persistedState.AXelements[id]);
}
return Promise.resolve({elements: arr});

View File

@@ -49,7 +49,7 @@ function constructPersistedState(axMode: boolean): PersistedState {
let state = constructPersistedState(false);
function populateChildren(state: PersistedState, axMode: boolean) {
let elements = {};
const elements = {};
elements['root'] = constructElement('root', 'root view', [
'child0',
'child1',
@@ -95,7 +95,7 @@ beforeEach(() => {
});
test('test the searchNode for root in axMode false', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'root',
false,
@@ -115,7 +115,7 @@ test('test the searchNode for root in axMode false', async () => {
test('test the searchNode for root in axMode true', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.AXelements['root'],
'RoOT',
true,
@@ -133,7 +133,7 @@ test('test the searchNode for root in axMode true', async () => {
});
test('test the searchNode which matches just one child', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'child0_child0',
false,
@@ -169,14 +169,14 @@ test('test the searchNode which matches just one child', async () => {
});
test('test the searchNode for which matches multiple child', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'child0',
false,
state,
);
expect(searchResult).toBeDefined();
let expectedSearchResult = {
const expectedSearchResult = {
id: 'root',
isMatch: false,
hasChildren: true,
@@ -231,14 +231,14 @@ test('test the searchNode for which matches multiple child', async () => {
});
test('test the searchNode, it should not be case sensitive', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'ChIlD0',
false,
state,
);
expect(searchResult).toBeDefined();
let expectedSearchResult = {
const expectedSearchResult = {
id: 'root',
isMatch: false,
hasChildren: true,
@@ -293,7 +293,7 @@ test('test the searchNode, it should not be case sensitive', async () => {
});
test('test the searchNode for non existent query', async () => {
let searchResult: ?SearchResultTree = await searchNodes(
const searchResult: ?SearchResultTree = await searchNodes(
state.elements['root'],
'Unknown query',
false,
@@ -303,22 +303,22 @@ test('test the searchNode for non existent query', async () => {
});
test('test the call method with getRoot', async () => {
let proxyClient = new ProxyArchiveClient(state);
let root: Element = await proxyClient.call('getRoot');
const proxyClient = new ProxyArchiveClient(state);
const root: Element = await proxyClient.call('getRoot');
expect(root).toEqual(state.elements['root']);
});
test('test the call method with getAXRoot', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let proxyClient = new ProxyArchiveClient(state);
let root: Element = await proxyClient.call('getAXRoot');
const proxyClient = new ProxyArchiveClient(state);
const root: Element = await proxyClient.call('getAXRoot');
expect(root).toEqual(state.AXelements['root']);
});
test('test the call method with getNodes', async () => {
let proxyClient = new ProxyArchiveClient(state);
let nodes: Array<Element> = await proxyClient.call('getNodes', {
const proxyClient = new ProxyArchiveClient(state);
const nodes: Array<Element> = await proxyClient.call('getNodes', {
ids: ['child0_child1', 'child1_child0'],
});
expect(nodes).toEqual({
@@ -350,8 +350,8 @@ test('test the call method with getNodes', async () => {
test('test the call method with getAXNodes', async () => {
state = constructPersistedState(true);
populateChildren(state, true);
let proxyClient = new ProxyArchiveClient(state);
let nodes: Array<Element> = await proxyClient.call('getAXNodes', {
const proxyClient = new ProxyArchiveClient(state);
const nodes: Array<Element> = await proxyClient.call('getAXNodes', {
ids: ['child0_child1', 'child1_child0'],
});
expect(nodes).toEqual({
@@ -381,7 +381,7 @@ test('test the call method with getAXNodes', async () => {
});
test('test different methods of calls with no params', async () => {
let proxyClient = new ProxyArchiveClient(state);
const proxyClient = new ProxyArchiveClient(state);
await expect(proxyClient.call('getNodes')).rejects.toThrow(
new Error('Called getNodes with no params'),
);
@@ -408,6 +408,6 @@ test('test different methods of calls with no params', async () => {
});
test('test call method isConsoleEnabled', () => {
let proxyClient = new ProxyArchiveClient(state);
const proxyClient = new ProxyArchiveClient(state);
return expect(proxyClient.call('isConsoleEnabled')).resolves.toBe(false);
});

View File

@@ -69,7 +69,7 @@ export default class LeakCanary extends FlipperPlugin<State> {
// collapsed state of the tree view
const newLeaks = processLeaks(results.leaks.slice(this.state.leaksCount));
let leaks = this.state.leaks;
const leaks = this.state.leaks;
for (let i = 0; i < newLeaks.length; i++) {
leaks.push(newLeaks[i]);
}

View File

@@ -53,8 +53,8 @@ function generateFieldsList(
lines: string[],
i: number,
): {|staticFields: {}, instanceFields: {}, packages: {}|} {
let staticFields = {};
let instanceFields = {};
const staticFields = {};
const instanceFields = {};
let staticValues = {};
let instanceValues = {};
@@ -62,7 +62,7 @@ function generateFieldsList(
let elementId = -1;
let elementIdStr = String(-1);
let packages = {};
const packages = {};
// Process everything between Details and Excluded Refs
while (
@@ -127,8 +127,8 @@ function processLeak(output: Leak[], leakInfo: string): Leak[] {
// Elements shows a Object's classname and package, wheras elementsSimple shows
// just its classname
let elements = {};
let elementsSimple = {};
const elements = {};
const elementsSimple = {};
let rootElementId = '';

View File

@@ -429,7 +429,7 @@ export default class LogTable extends FlipperDevicePlugin<
if (highlightedRows.size <= 0) {
// Check if the individual lines in the deeplinkPayload is matched or not.
const arr = deepLinkPayload.split('\n');
for (let msg of arr) {
for (const msg of arr) {
for (let i = rows.length - 1; i >= 0; i--) {
if (rows[i].filterValue && rows[i].filterValue.includes(msg)) {
highlightedRows.add(rows[i].key);

View File

@@ -129,7 +129,7 @@ test('convertRequestToCurlCommand: malicious POST data', () => {
});
test('convertRequestToCurlCommand: control characters', () => {
let request: Request = {
const request: Request = {
id: 'request id',
timestamp: 1234567890,
method: 'GET',
@@ -138,7 +138,7 @@ test('convertRequestToCurlCommand: control characters', () => {
data: btoa('some=\u0007 \u0009 \u000C \u001B&other=param'),
};
let command = convertRequestToCurlCommand(request);
const command = convertRequestToCurlCommand(request);
expect(command).toEqual(
"curl -v -X GET 'https://fbflipper.com/' -d $'some=\\u07 \\u09 \\u0c \\u1b&other=param'",
);

View File

@@ -90,8 +90,8 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
reducers = {
UpdateSharedPreferences(state: SharedPreferencesState, results: Object) {
let update = results.update;
let entry = state.sharedPreferences[update.name] || {changesList: []};
const update = results.update;
const entry = state.sharedPreferences[update.name] || {changesList: []};
entry.preferences = update.preferences;
state.sharedPreferences[update.name] = entry;
return {
@@ -170,7 +170,7 @@ export default class extends FlipperPlugin<SharedPreferencesState> {
preferenceValue: newValue,
})
.then((results: SharedPreferences) => {
let update = {
const update = {
name: this.state.selectedPreferences,
preferences: results,
};