id
int32 0
58k
| repo
stringlengths 5
67
| path
stringlengths 4
116
| func_name
stringlengths 0
58
| original_string
stringlengths 52
373k
| language
stringclasses 1
value | code
stringlengths 52
373k
| code_tokens
sequence | docstring
stringlengths 4
11.8k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 86
226
|
---|---|---|---|---|---|---|---|---|---|---|---|
8,500 | eventbrite/britecharts | src/charts/stacked-area.js | buildLayers | function buildLayers() {
dataByDateFormatted = dataByDate
.map(d => assign({}, d, d.values))
.map(d => {
Object.keys(d).forEach(k => {
const entry = d[k];
if (entry && entry.name) {
d[entry.name] = entry.value;
}
});
return assign({}, d, {
date: new Date(d['key'])
});
});
dataByDateZeroed = dataByDate
.map(d => assign({}, d, d.values))
.map(d => {
Object.keys(d).forEach(k => {
const entry = d[k];
if (entry && entry.name) {
d[entry.name] = 0;
}
});
return assign({}, d, {
date: new Date(d['key'])
});
});
let initialTotalsObject = uniq(data.map(getName))
.reduce((memo, key) => (
assign({}, memo, {[key]: 0})
), {});
let totals = data
.reduce((memo, item) => (
assign({}, memo, {[item.name]: memo[item.name] += item.value})
), initialTotalsObject);
order = topicsOrder || formatOrder(totals);
let stack3 = d3Shape.stack()
.keys(order)
.order(d3Shape.stackOrderNone)
.offset(d3Shape.stackOffsetNone);
layersInitial = stack3(dataByDateZeroed);
layers = stack3(dataByDateFormatted);
} | javascript | function buildLayers() {
dataByDateFormatted = dataByDate
.map(d => assign({}, d, d.values))
.map(d => {
Object.keys(d).forEach(k => {
const entry = d[k];
if (entry && entry.name) {
d[entry.name] = entry.value;
}
});
return assign({}, d, {
date: new Date(d['key'])
});
});
dataByDateZeroed = dataByDate
.map(d => assign({}, d, d.values))
.map(d => {
Object.keys(d).forEach(k => {
const entry = d[k];
if (entry && entry.name) {
d[entry.name] = 0;
}
});
return assign({}, d, {
date: new Date(d['key'])
});
});
let initialTotalsObject = uniq(data.map(getName))
.reduce((memo, key) => (
assign({}, memo, {[key]: 0})
), {});
let totals = data
.reduce((memo, item) => (
assign({}, memo, {[item.name]: memo[item.name] += item.value})
), initialTotalsObject);
order = topicsOrder || formatOrder(totals);
let stack3 = d3Shape.stack()
.keys(order)
.order(d3Shape.stackOrderNone)
.offset(d3Shape.stackOffsetNone);
layersInitial = stack3(dataByDateZeroed);
layers = stack3(dataByDateFormatted);
} | [
"function",
"buildLayers",
"(",
")",
"{",
"dataByDateFormatted",
"=",
"dataByDate",
".",
"map",
"(",
"d",
"=>",
"assign",
"(",
"{",
"}",
",",
"d",
",",
"d",
".",
"values",
")",
")",
".",
"map",
"(",
"d",
"=>",
"{",
"Object",
".",
"keys",
"(",
"d",
")",
".",
"forEach",
"(",
"k",
"=>",
"{",
"const",
"entry",
"=",
"d",
"[",
"k",
"]",
";",
"if",
"(",
"entry",
"&&",
"entry",
".",
"name",
")",
"{",
"d",
"[",
"entry",
".",
"name",
"]",
"=",
"entry",
".",
"value",
";",
"}",
"}",
")",
";",
"return",
"assign",
"(",
"{",
"}",
",",
"d",
",",
"{",
"date",
":",
"new",
"Date",
"(",
"d",
"[",
"'key'",
"]",
")",
"}",
")",
";",
"}",
")",
";",
"dataByDateZeroed",
"=",
"dataByDate",
".",
"map",
"(",
"d",
"=>",
"assign",
"(",
"{",
"}",
",",
"d",
",",
"d",
".",
"values",
")",
")",
".",
"map",
"(",
"d",
"=>",
"{",
"Object",
".",
"keys",
"(",
"d",
")",
".",
"forEach",
"(",
"k",
"=>",
"{",
"const",
"entry",
"=",
"d",
"[",
"k",
"]",
";",
"if",
"(",
"entry",
"&&",
"entry",
".",
"name",
")",
"{",
"d",
"[",
"entry",
".",
"name",
"]",
"=",
"0",
";",
"}",
"}",
")",
";",
"return",
"assign",
"(",
"{",
"}",
",",
"d",
",",
"{",
"date",
":",
"new",
"Date",
"(",
"d",
"[",
"'key'",
"]",
")",
"}",
")",
";",
"}",
")",
";",
"let",
"initialTotalsObject",
"=",
"uniq",
"(",
"data",
".",
"map",
"(",
"getName",
")",
")",
".",
"reduce",
"(",
"(",
"memo",
",",
"key",
")",
"=>",
"(",
"assign",
"(",
"{",
"}",
",",
"memo",
",",
"{",
"[",
"key",
"]",
":",
"0",
"}",
")",
")",
",",
"{",
"}",
")",
";",
"let",
"totals",
"=",
"data",
".",
"reduce",
"(",
"(",
"memo",
",",
"item",
")",
"=>",
"(",
"assign",
"(",
"{",
"}",
",",
"memo",
",",
"{",
"[",
"item",
".",
"name",
"]",
":",
"memo",
"[",
"item",
".",
"name",
"]",
"+=",
"item",
".",
"value",
"}",
")",
")",
",",
"initialTotalsObject",
")",
";",
"order",
"=",
"topicsOrder",
"||",
"formatOrder",
"(",
"totals",
")",
";",
"let",
"stack3",
"=",
"d3Shape",
".",
"stack",
"(",
")",
".",
"keys",
"(",
"order",
")",
".",
"order",
"(",
"d3Shape",
".",
"stackOrderNone",
")",
".",
"offset",
"(",
"d3Shape",
".",
"stackOffsetNone",
")",
";",
"layersInitial",
"=",
"stack3",
"(",
"dataByDateZeroed",
")",
";",
"layers",
"=",
"stack3",
"(",
"dataByDateFormatted",
")",
";",
"}"
] | Builds the stacked layers layout
@return {D3Layout} Layout for drawing the chart
@private | [
"Builds",
"the",
"stacked",
"layers",
"layout"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L380-L432 |
8,501 | eventbrite/britecharts | src/charts/stacked-area.js | formatOrder | function formatOrder(totals) {
let order = Object.keys(totals)
.sort((a, b) => {
if (totals[a] > totals[b]) return -1;
if (totals[a] === totals[b]) return 0;
return 1;
});
let otherIndex = order.indexOf('Other');
if (otherIndex >= 0) {
let other = order.splice(otherIndex, 1);
order = order.concat(other);
}
return order;
} | javascript | function formatOrder(totals) {
let order = Object.keys(totals)
.sort((a, b) => {
if (totals[a] > totals[b]) return -1;
if (totals[a] === totals[b]) return 0;
return 1;
});
let otherIndex = order.indexOf('Other');
if (otherIndex >= 0) {
let other = order.splice(otherIndex, 1);
order = order.concat(other);
}
return order;
} | [
"function",
"formatOrder",
"(",
"totals",
")",
"{",
"let",
"order",
"=",
"Object",
".",
"keys",
"(",
"totals",
")",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"{",
"if",
"(",
"totals",
"[",
"a",
"]",
">",
"totals",
"[",
"b",
"]",
")",
"return",
"-",
"1",
";",
"if",
"(",
"totals",
"[",
"a",
"]",
"===",
"totals",
"[",
"b",
"]",
")",
"return",
"0",
";",
"return",
"1",
";",
"}",
")",
";",
"let",
"otherIndex",
"=",
"order",
".",
"indexOf",
"(",
"'Other'",
")",
";",
"if",
"(",
"otherIndex",
">=",
"0",
")",
"{",
"let",
"other",
"=",
"order",
".",
"splice",
"(",
"otherIndex",
",",
"1",
")",
";",
"order",
"=",
"order",
".",
"concat",
"(",
"other",
")",
";",
"}",
"return",
"order",
";",
"}"
] | Takes an object with all topics as keys and their aggregate totals as values,
sorts them into a list by descending total value and
moves "Other" to the end
@param {Object} totals Keys of all the topics and their corresponding totals
@return {Array} List of topic names in aggregate order | [
"Takes",
"an",
"object",
"with",
"all",
"topics",
"as",
"keys",
"and",
"their",
"aggregate",
"totals",
"as",
"values",
"sorts",
"them",
"into",
"a",
"list",
"by",
"descending",
"total",
"value",
"and",
"moves",
"Other",
"to",
"the",
"end"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L441-L459 |
8,502 | eventbrite/britecharts | src/charts/stacked-area.js | createFakeData | function createFakeData() {
const numDays = diffDays(emptyDataConfig.minDate, emptyDataConfig.maxDate)
const emptyArray = Array.apply(null, Array(numDays));
isUsingFakeData = true;
return [
...emptyArray.map((el, i) => ({
[dateLabel]: addDays(emptyDataConfig.minDate, i),
[valueLabel]: 0,
[keyLabel]: '1',
})),
...emptyArray.map((el, i) => ({
[dateLabel]: addDays(emptyDataConfig.minDate, i),
[valueLabel]: 0,
[keyLabel]: '2',
}))
];
} | javascript | function createFakeData() {
const numDays = diffDays(emptyDataConfig.minDate, emptyDataConfig.maxDate)
const emptyArray = Array.apply(null, Array(numDays));
isUsingFakeData = true;
return [
...emptyArray.map((el, i) => ({
[dateLabel]: addDays(emptyDataConfig.minDate, i),
[valueLabel]: 0,
[keyLabel]: '1',
})),
...emptyArray.map((el, i) => ({
[dateLabel]: addDays(emptyDataConfig.minDate, i),
[valueLabel]: 0,
[keyLabel]: '2',
}))
];
} | [
"function",
"createFakeData",
"(",
")",
"{",
"const",
"numDays",
"=",
"diffDays",
"(",
"emptyDataConfig",
".",
"minDate",
",",
"emptyDataConfig",
".",
"maxDate",
")",
"const",
"emptyArray",
"=",
"Array",
".",
"apply",
"(",
"null",
",",
"Array",
"(",
"numDays",
")",
")",
";",
"isUsingFakeData",
"=",
"true",
";",
"return",
"[",
"...",
"emptyArray",
".",
"map",
"(",
"(",
"el",
",",
"i",
")",
"=>",
"(",
"{",
"[",
"dateLabel",
"]",
":",
"addDays",
"(",
"emptyDataConfig",
".",
"minDate",
",",
"i",
")",
",",
"[",
"valueLabel",
"]",
":",
"0",
",",
"[",
"keyLabel",
"]",
":",
"'1'",
",",
"}",
")",
")",
",",
"...",
"emptyArray",
".",
"map",
"(",
"(",
"el",
",",
"i",
")",
"=>",
"(",
"{",
"[",
"dateLabel",
"]",
":",
"addDays",
"(",
"emptyDataConfig",
".",
"minDate",
",",
"i",
")",
",",
"[",
"valueLabel",
"]",
":",
"0",
",",
"[",
"keyLabel",
"]",
":",
"'2'",
",",
"}",
")",
")",
"]",
";",
"}"
] | Creates fake data for when data is an empty array
@return {array} Fake data built from emptyDataConfig settings | [
"Creates",
"fake",
"data",
"for",
"when",
"data",
"is",
"an",
"empty",
"array"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L504-L523 |
8,503 | eventbrite/britecharts | src/charts/stacked-area.js | cleanData | function cleanData(originalData) {
originalData = originalData.length === 0 ? createFakeData() : originalData;
return originalData.reduce((acc, d) => {
d.date = new Date(d[dateLabel]),
d.value = +d[valueLabel]
return [...acc, d];
}, []);
} | javascript | function cleanData(originalData) {
originalData = originalData.length === 0 ? createFakeData() : originalData;
return originalData.reduce((acc, d) => {
d.date = new Date(d[dateLabel]),
d.value = +d[valueLabel]
return [...acc, d];
}, []);
} | [
"function",
"cleanData",
"(",
"originalData",
")",
"{",
"originalData",
"=",
"originalData",
".",
"length",
"===",
"0",
"?",
"createFakeData",
"(",
")",
":",
"originalData",
";",
"return",
"originalData",
".",
"reduce",
"(",
"(",
"acc",
",",
"d",
")",
"=>",
"{",
"d",
".",
"date",
"=",
"new",
"Date",
"(",
"d",
"[",
"dateLabel",
"]",
")",
",",
"d",
".",
"value",
"=",
"+",
"d",
"[",
"valueLabel",
"]",
"return",
"[",
"...",
"acc",
",",
"d",
"]",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Cleaning data casting the values and dates to the proper type while keeping
the rest of properties on the data. It creates fake data is the data is empty.
@param {areaChartData} originalData Raw data from the container
@return {areaChartData} Parsed data with values and dates
@private | [
"Cleaning",
"data",
"casting",
"the",
"values",
"and",
"dates",
"to",
"the",
"proper",
"type",
"while",
"keeping",
"the",
"rest",
"of",
"properties",
"on",
"the",
"data",
".",
"It",
"creates",
"fake",
"data",
"is",
"the",
"data",
"is",
"empty",
"."
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L532-L541 |
8,504 | eventbrite/britecharts | src/charts/stacked-area.js | drawEmptyDataLine | function drawEmptyDataLine() {
let emptyDataLine = d3Shape.line()
.x( (d) => xScale(d.date) )
.y( () => yScale(0) - 1 );
let chartGroup = svg.select('.chart-group');
chartGroup
.append('path')
.attr('class', 'empty-data-line')
.attr('d', emptyDataLine(dataByDateFormatted))
.style('stroke', 'url(#empty-data-line-gradient)');
chartGroup
.append('linearGradient')
.attr('id', 'empty-data-line-gradient')
.attr('gradientUnits', 'userSpaceOnUse')
.attr('x1', 0)
.attr('x2', xScale(data[data.length - 1].date))
.attr('y1', 0)
.attr('y2', 0)
.selectAll('stop')
.data([
{offset: '0%', color: lineGradient[0]},
{offset: '100%', color: lineGradient[1]}
])
.enter()
.append('stop')
.attr('offset', ({offset}) => offset)
.attr('stop-color', ({color}) => color);
} | javascript | function drawEmptyDataLine() {
let emptyDataLine = d3Shape.line()
.x( (d) => xScale(d.date) )
.y( () => yScale(0) - 1 );
let chartGroup = svg.select('.chart-group');
chartGroup
.append('path')
.attr('class', 'empty-data-line')
.attr('d', emptyDataLine(dataByDateFormatted))
.style('stroke', 'url(#empty-data-line-gradient)');
chartGroup
.append('linearGradient')
.attr('id', 'empty-data-line-gradient')
.attr('gradientUnits', 'userSpaceOnUse')
.attr('x1', 0)
.attr('x2', xScale(data[data.length - 1].date))
.attr('y1', 0)
.attr('y2', 0)
.selectAll('stop')
.data([
{offset: '0%', color: lineGradient[0]},
{offset: '100%', color: lineGradient[1]}
])
.enter()
.append('stop')
.attr('offset', ({offset}) => offset)
.attr('stop-color', ({color}) => color);
} | [
"function",
"drawEmptyDataLine",
"(",
")",
"{",
"let",
"emptyDataLine",
"=",
"d3Shape",
".",
"line",
"(",
")",
".",
"x",
"(",
"(",
"d",
")",
"=>",
"xScale",
"(",
"d",
".",
"date",
")",
")",
".",
"y",
"(",
"(",
")",
"=>",
"yScale",
"(",
"0",
")",
"-",
"1",
")",
";",
"let",
"chartGroup",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
";",
"chartGroup",
".",
"append",
"(",
"'path'",
")",
".",
"attr",
"(",
"'class'",
",",
"'empty-data-line'",
")",
".",
"attr",
"(",
"'d'",
",",
"emptyDataLine",
"(",
"dataByDateFormatted",
")",
")",
".",
"style",
"(",
"'stroke'",
",",
"'url(#empty-data-line-gradient)'",
")",
";",
"chartGroup",
".",
"append",
"(",
"'linearGradient'",
")",
".",
"attr",
"(",
"'id'",
",",
"'empty-data-line-gradient'",
")",
".",
"attr",
"(",
"'gradientUnits'",
",",
"'userSpaceOnUse'",
")",
".",
"attr",
"(",
"'x1'",
",",
"0",
")",
".",
"attr",
"(",
"'x2'",
",",
"xScale",
"(",
"data",
"[",
"data",
".",
"length",
"-",
"1",
"]",
".",
"date",
")",
")",
".",
"attr",
"(",
"'y1'",
",",
"0",
")",
".",
"attr",
"(",
"'y2'",
",",
"0",
")",
".",
"selectAll",
"(",
"'stop'",
")",
".",
"data",
"(",
"[",
"{",
"offset",
":",
"'0%'",
",",
"color",
":",
"lineGradient",
"[",
"0",
"]",
"}",
",",
"{",
"offset",
":",
"'100%'",
",",
"color",
":",
"lineGradient",
"[",
"1",
"]",
"}",
"]",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'stop'",
")",
".",
"attr",
"(",
"'offset'",
",",
"(",
"{",
"offset",
"}",
")",
"=>",
"offset",
")",
".",
"attr",
"(",
"'stop-color'",
",",
"(",
"{",
"color",
"}",
")",
"=>",
"color",
")",
";",
"}"
] | Draws an empty line when the data is all zero
@private | [
"Draws",
"an",
"empty",
"line",
"when",
"the",
"data",
"is",
"all",
"zero"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L705-L735 |
8,505 | eventbrite/britecharts | src/charts/stacked-area.js | drawVerticalMarker | function drawVerticalMarker() {
// Not ideal, we need to figure out how to call exit for nested elements
if (verticalMarkerContainer) {
svg.selectAll('.vertical-marker-container').remove();
}
verticalMarkerContainer = svg.select('.metadata-group')
.append('g')
.attr('class', 'vertical-marker-container')
.attr('transform', 'translate(9999, 0)');
verticalMarkerLine = verticalMarkerContainer.selectAll('path')
.data([{
x1: 0,
y1: 0,
x2: 0,
y2: 0
}])
.enter()
.append('line')
.classed('vertical-marker', true)
.attr('x1', 0)
.attr('y1', chartHeight)
.attr('x2', 0)
.attr('y2', 0);
} | javascript | function drawVerticalMarker() {
// Not ideal, we need to figure out how to call exit for nested elements
if (verticalMarkerContainer) {
svg.selectAll('.vertical-marker-container').remove();
}
verticalMarkerContainer = svg.select('.metadata-group')
.append('g')
.attr('class', 'vertical-marker-container')
.attr('transform', 'translate(9999, 0)');
verticalMarkerLine = verticalMarkerContainer.selectAll('path')
.data([{
x1: 0,
y1: 0,
x2: 0,
y2: 0
}])
.enter()
.append('line')
.classed('vertical-marker', true)
.attr('x1', 0)
.attr('y1', chartHeight)
.attr('x2', 0)
.attr('y2', 0);
} | [
"function",
"drawVerticalMarker",
"(",
")",
"{",
"// Not ideal, we need to figure out how to call exit for nested elements",
"if",
"(",
"verticalMarkerContainer",
")",
"{",
"svg",
".",
"selectAll",
"(",
"'.vertical-marker-container'",
")",
".",
"remove",
"(",
")",
";",
"}",
"verticalMarkerContainer",
"=",
"svg",
".",
"select",
"(",
"'.metadata-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"attr",
"(",
"'class'",
",",
"'vertical-marker-container'",
")",
".",
"attr",
"(",
"'transform'",
",",
"'translate(9999, 0)'",
")",
";",
"verticalMarkerLine",
"=",
"verticalMarkerContainer",
".",
"selectAll",
"(",
"'path'",
")",
".",
"data",
"(",
"[",
"{",
"x1",
":",
"0",
",",
"y1",
":",
"0",
",",
"x2",
":",
"0",
",",
"y2",
":",
"0",
"}",
"]",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'line'",
")",
".",
"classed",
"(",
"'vertical-marker'",
",",
"true",
")",
".",
"attr",
"(",
"'x1'",
",",
"0",
")",
".",
"attr",
"(",
"'y1'",
",",
"chartHeight",
")",
".",
"attr",
"(",
"'x2'",
",",
"0",
")",
".",
"attr",
"(",
"'y2'",
",",
"0",
")",
";",
"}"
] | Creates the vertical marker
@return void | [
"Creates",
"the",
"vertical",
"marker"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L855-L880 |
8,506 | eventbrite/britecharts | src/charts/stacked-area.js | getDataByDate | function getDataByDate(data) {
return d3Collection.nest()
.key(getDate)
.entries(
data.sort((a, b) => a.date - b.date)
)
.map(d => {
return assign({}, d, {
date: new Date(d.key)
});
});
// let b = d3Collection.nest()
// .key(getDate).sortKeys(d3Array.ascending)
// .entries(data);
} | javascript | function getDataByDate(data) {
return d3Collection.nest()
.key(getDate)
.entries(
data.sort((a, b) => a.date - b.date)
)
.map(d => {
return assign({}, d, {
date: new Date(d.key)
});
});
// let b = d3Collection.nest()
// .key(getDate).sortKeys(d3Array.ascending)
// .entries(data);
} | [
"function",
"getDataByDate",
"(",
"data",
")",
"{",
"return",
"d3Collection",
".",
"nest",
"(",
")",
".",
"key",
"(",
"getDate",
")",
".",
"entries",
"(",
"data",
".",
"sort",
"(",
"(",
"a",
",",
"b",
")",
"=>",
"a",
".",
"date",
"-",
"b",
".",
"date",
")",
")",
".",
"map",
"(",
"d",
"=>",
"{",
"return",
"assign",
"(",
"{",
"}",
",",
"d",
",",
"{",
"date",
":",
"new",
"Date",
"(",
"d",
".",
"key",
")",
"}",
")",
";",
"}",
")",
";",
"// let b = d3Collection.nest()",
"// .key(getDate).sortKeys(d3Array.ascending)",
"// .entries(data);",
"}"
] | Orders the data by date for consumption on the chart tooltip
@param {areaChartData} data Chart data
@return {Object[]} Chart data ordered by date
@private | [
"Orders",
"the",
"data",
"by",
"date",
"for",
"consumption",
"on",
"the",
"chart",
"tooltip"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L897-L912 |
8,507 | eventbrite/britecharts | src/charts/stacked-area.js | getMaxValueByDate | function getMaxValueByDate() {
let keys = uniq(data.map(o => o.name));
let maxValueByDate = d3Array.max(dataByDateFormatted, function(d){
let vals = keys.map((key) => d[key]);
return d3Array.sum(vals);
});
return maxValueByDate;
} | javascript | function getMaxValueByDate() {
let keys = uniq(data.map(o => o.name));
let maxValueByDate = d3Array.max(dataByDateFormatted, function(d){
let vals = keys.map((key) => d[key]);
return d3Array.sum(vals);
});
return maxValueByDate;
} | [
"function",
"getMaxValueByDate",
"(",
")",
"{",
"let",
"keys",
"=",
"uniq",
"(",
"data",
".",
"map",
"(",
"o",
"=>",
"o",
".",
"name",
")",
")",
";",
"let",
"maxValueByDate",
"=",
"d3Array",
".",
"max",
"(",
"dataByDateFormatted",
",",
"function",
"(",
"d",
")",
"{",
"let",
"vals",
"=",
"keys",
".",
"map",
"(",
"(",
"key",
")",
"=>",
"d",
"[",
"key",
"]",
")",
";",
"return",
"d3Array",
".",
"sum",
"(",
"vals",
")",
";",
"}",
")",
";",
"return",
"maxValueByDate",
";",
"}"
] | Computes the maximum sum of values for any date
@return {Number} Max value | [
"Computes",
"the",
"maximum",
"sum",
"of",
"values",
"for",
"any",
"date"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L919-L928 |
8,508 | eventbrite/britecharts | src/charts/stacked-area.js | setEpsilon | function setEpsilon() {
let dates = dataByDate.map(({date}) => date);
epsilon = (xScale(dates[1]) - xScale(dates[0])) / 2;
} | javascript | function setEpsilon() {
let dates = dataByDate.map(({date}) => date);
epsilon = (xScale(dates[1]) - xScale(dates[0])) / 2;
} | [
"function",
"setEpsilon",
"(",
")",
"{",
"let",
"dates",
"=",
"dataByDate",
".",
"map",
"(",
"(",
"{",
"date",
"}",
")",
"=>",
"date",
")",
";",
"epsilon",
"=",
"(",
"xScale",
"(",
"dates",
"[",
"1",
"]",
")",
"-",
"xScale",
"(",
"dates",
"[",
"0",
"]",
")",
")",
"/",
"2",
";",
"}"
] | Epsilon is the value given to the number representing half of the distance in
pixels between two date data points
@return {Number} half distance between any two points | [
"Epsilon",
"is",
"the",
"value",
"given",
"to",
"the",
"number",
"representing",
"half",
"of",
"the",
"distance",
"in",
"pixels",
"between",
"two",
"date",
"data",
"points"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L948-L952 |
8,509 | eventbrite/britecharts | src/charts/stacked-area.js | handleMouseOver | function handleMouseOver(e, d) {
overlay.style('display', 'block');
verticalMarkerLine.classed('bc-is-active', true);
dispatcher.call('customMouseOver', e, d, d3Selection.mouse(e));
} | javascript | function handleMouseOver(e, d) {
overlay.style('display', 'block');
verticalMarkerLine.classed('bc-is-active', true);
dispatcher.call('customMouseOver', e, d, d3Selection.mouse(e));
} | [
"function",
"handleMouseOver",
"(",
"e",
",",
"d",
")",
"{",
"overlay",
".",
"style",
"(",
"'display'",
",",
"'block'",
")",
";",
"verticalMarkerLine",
".",
"classed",
"(",
"'bc-is-active'",
",",
"true",
")",
";",
"dispatcher",
".",
"call",
"(",
"'customMouseOver'",
",",
"e",
",",
"d",
",",
"d3Selection",
".",
"mouse",
"(",
"e",
")",
")",
";",
"}"
] | Mouseover handler, shows overlay and adds active class to verticalMarkerLine
@private | [
"Mouseover",
"handler",
"shows",
"overlay",
"and",
"adds",
"active",
"class",
"to",
"verticalMarkerLine"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L994-L999 |
8,510 | eventbrite/britecharts | src/charts/stacked-area.js | handleTouchMove | function handleTouchMove(e, d) {
dispatcher.call('customTouchMove', e, d, d3Selection.touch(e));
} | javascript | function handleTouchMove(e, d) {
dispatcher.call('customTouchMove', e, d, d3Selection.touch(e));
} | [
"function",
"handleTouchMove",
"(",
"e",
",",
"d",
")",
"{",
"dispatcher",
".",
"call",
"(",
"'customTouchMove'",
",",
"e",
",",
"d",
",",
"d3Selection",
".",
"touch",
"(",
"e",
")",
")",
";",
"}"
] | Touchmove highlighted points
It will only pass the information with the event
@private | [
"Touchmove",
"highlighted",
"points",
"It",
"will",
"only",
"pass",
"the",
"information",
"with",
"the",
"event"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L1006-L1008 |
8,511 | eventbrite/britecharts | src/charts/stacked-area.js | handleHighlightClick | function handleHighlightClick(e, d) {
dispatcher.call('customDataEntryClick', e, d, d3Selection.mouse(e));
} | javascript | function handleHighlightClick(e, d) {
dispatcher.call('customDataEntryClick', e, d, d3Selection.mouse(e));
} | [
"function",
"handleHighlightClick",
"(",
"e",
",",
"d",
")",
"{",
"dispatcher",
".",
"call",
"(",
"'customDataEntryClick'",
",",
"e",
",",
"d",
",",
"d3Selection",
".",
"mouse",
"(",
"e",
")",
")",
";",
"}"
] | Mouseclick handler over one of the highlight points
It will only pass the information with the event
@private | [
"Mouseclick",
"handler",
"over",
"one",
"of",
"the",
"highlight",
"points",
"It",
"will",
"only",
"pass",
"the",
"information",
"with",
"the",
"event"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/stacked-area.js#L1015-L1017 |
8,512 | eventbrite/britecharts | src/charts/legend.js | adjustLines | function adjustLines() {
let lineWidth = svg.select('.legend-line').node().getBoundingClientRect().width + markerSize;
let lineWidthSpace = chartWidth - lineWidth;
if (lineWidthSpace <= 0) {
splitInLines();
}
centerInlineLegendOnSVG();
} | javascript | function adjustLines() {
let lineWidth = svg.select('.legend-line').node().getBoundingClientRect().width + markerSize;
let lineWidthSpace = chartWidth - lineWidth;
if (lineWidthSpace <= 0) {
splitInLines();
}
centerInlineLegendOnSVG();
} | [
"function",
"adjustLines",
"(",
")",
"{",
"let",
"lineWidth",
"=",
"svg",
".",
"select",
"(",
"'.legend-line'",
")",
".",
"node",
"(",
")",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
"+",
"markerSize",
";",
"let",
"lineWidthSpace",
"=",
"chartWidth",
"-",
"lineWidth",
";",
"if",
"(",
"lineWidthSpace",
"<=",
"0",
")",
"{",
"splitInLines",
"(",
")",
";",
"}",
"centerInlineLegendOnSVG",
"(",
")",
";",
"}"
] | Depending on the size of the horizontal legend, we are going to add a new
line with the last entry of the legend
@return {void}
@private | [
"Depending",
"on",
"the",
"size",
"of",
"the",
"horizontal",
"legend",
"we",
"are",
"going",
"to",
"add",
"a",
"new",
"line",
"with",
"the",
"last",
"entry",
"of",
"the",
"legend"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L146-L155 |
8,513 | eventbrite/britecharts | src/charts/legend.js | buildContainerGroups | function buildContainerGroups() {
let container = svg
.append('g')
.classed('legend-container-group', true)
.attr('transform', `translate(${margin.left},${margin.top})`);
container
.append('g')
.classed('legend-group', true);
} | javascript | function buildContainerGroups() {
let container = svg
.append('g')
.classed('legend-container-group', true)
.attr('transform', `translate(${margin.left},${margin.top})`);
container
.append('g')
.classed('legend-group', true);
} | [
"function",
"buildContainerGroups",
"(",
")",
"{",
"let",
"container",
"=",
"svg",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-container-group'",
",",
"true",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"margin",
".",
"left",
"}",
"${",
"margin",
".",
"top",
"}",
"`",
")",
";",
"container",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-group'",
",",
"true",
")",
";",
"}"
] | Builds containers for the legend
Also applies the Margin convention
@private | [
"Builds",
"containers",
"for",
"the",
"legend",
"Also",
"applies",
"the",
"Margin",
"convention"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L162-L171 |
8,514 | eventbrite/britecharts | src/charts/legend.js | centerInlineLegendOnSVG | function centerInlineLegendOnSVG() {
let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width + getLineElementMargin();
let emptySpace = width - legendGroupSize;
let newXPosition = (emptySpace/2);
if (emptySpace > 0) {
svg.select('g.legend-container-group')
.attr('transform', `translate(${newXPosition},0)`)
}
} | javascript | function centerInlineLegendOnSVG() {
let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width + getLineElementMargin();
let emptySpace = width - legendGroupSize;
let newXPosition = (emptySpace/2);
if (emptySpace > 0) {
svg.select('g.legend-container-group')
.attr('transform', `translate(${newXPosition},0)`)
}
} | [
"function",
"centerInlineLegendOnSVG",
"(",
")",
"{",
"let",
"legendGroupSize",
"=",
"svg",
".",
"select",
"(",
"'g.legend-container-group'",
")",
".",
"node",
"(",
")",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
"+",
"getLineElementMargin",
"(",
")",
";",
"let",
"emptySpace",
"=",
"width",
"-",
"legendGroupSize",
";",
"let",
"newXPosition",
"=",
"(",
"emptySpace",
"/",
"2",
")",
";",
"if",
"(",
"emptySpace",
">",
"0",
")",
"{",
"svg",
".",
"select",
"(",
"'g.legend-container-group'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"newXPosition",
"}",
"`",
")",
"}",
"}"
] | Centers the legend on the chart given that is a single line of labels
@return {void}
@private | [
"Centers",
"the",
"legend",
"on",
"the",
"chart",
"given",
"that",
"is",
"a",
"single",
"line",
"of",
"labels"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L207-L216 |
8,515 | eventbrite/britecharts | src/charts/legend.js | centerVerticalLegendOnSVG | function centerVerticalLegendOnSVG() {
let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width;
let emptySpace = width - legendGroupSize;
let newXPosition = (emptySpace / 2) - (legendGroupSize / 2);
if (emptySpace > 0) {
svg.select('g.legend-container-group')
.attr('transform', `translate(${newXPosition},0)`)
}
} | javascript | function centerVerticalLegendOnSVG() {
let legendGroupSize = svg.select('g.legend-container-group').node().getBoundingClientRect().width;
let emptySpace = width - legendGroupSize;
let newXPosition = (emptySpace / 2) - (legendGroupSize / 2);
if (emptySpace > 0) {
svg.select('g.legend-container-group')
.attr('transform', `translate(${newXPosition},0)`)
}
} | [
"function",
"centerVerticalLegendOnSVG",
"(",
")",
"{",
"let",
"legendGroupSize",
"=",
"svg",
".",
"select",
"(",
"'g.legend-container-group'",
")",
".",
"node",
"(",
")",
".",
"getBoundingClientRect",
"(",
")",
".",
"width",
";",
"let",
"emptySpace",
"=",
"width",
"-",
"legendGroupSize",
";",
"let",
"newXPosition",
"=",
"(",
"emptySpace",
"/",
"2",
")",
"-",
"(",
"legendGroupSize",
"/",
"2",
")",
";",
"if",
"(",
"emptySpace",
">",
"0",
")",
"{",
"svg",
".",
"select",
"(",
"'g.legend-container-group'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"newXPosition",
"}",
"`",
")",
"}",
"}"
] | Centers the legend on the chart given that is a stack of labels
@return {void}
@private | [
"Centers",
"the",
"legend",
"on",
"the",
"chart",
"given",
"that",
"is",
"a",
"stack",
"of",
"labels"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L223-L232 |
8,516 | eventbrite/britecharts | src/charts/legend.js | cleanData | function cleanData(data) {
hasQuantities = data.filter(hasQuantity).length === data.length;
return data
.reduce((acc, d) => {
if (d.quantity !== undefined && d.quantity !== null) {
d.quantity = +d.quantity;
}
d.name = String(d.name);
d.id = +d.id;
return [...acc, d];
}, []);
} | javascript | function cleanData(data) {
hasQuantities = data.filter(hasQuantity).length === data.length;
return data
.reduce((acc, d) => {
if (d.quantity !== undefined && d.quantity !== null) {
d.quantity = +d.quantity;
}
d.name = String(d.name);
d.id = +d.id;
return [...acc, d];
}, []);
} | [
"function",
"cleanData",
"(",
"data",
")",
"{",
"hasQuantities",
"=",
"data",
".",
"filter",
"(",
"hasQuantity",
")",
".",
"length",
"===",
"data",
".",
"length",
";",
"return",
"data",
".",
"reduce",
"(",
"(",
"acc",
",",
"d",
")",
"=>",
"{",
"if",
"(",
"d",
".",
"quantity",
"!==",
"undefined",
"&&",
"d",
".",
"quantity",
"!==",
"null",
")",
"{",
"d",
".",
"quantity",
"=",
"+",
"d",
".",
"quantity",
";",
"}",
"d",
".",
"name",
"=",
"String",
"(",
"d",
".",
"name",
")",
";",
"d",
".",
"id",
"=",
"+",
"d",
".",
"id",
";",
"return",
"[",
"...",
"acc",
",",
"d",
"]",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Makes sure the types of the data are right and checks if it has quantities
@param {LegendChartData} data
@private | [
"Makes",
"sure",
"the",
"types",
"of",
"the",
"data",
"are",
"right",
"and",
"checks",
"if",
"it",
"has",
"quantities"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L239-L252 |
8,517 | eventbrite/britecharts | src/charts/legend.js | drawHorizontalLegend | function drawHorizontalLegend() {
let xOffset = markerSize;
svg.select('.legend-group')
.selectAll('g')
.remove();
// We want a single line
svg.select('.legend-group')
.append('g')
.classed('legend-line', true);
// And one entry per data item
entries = svg.select('.legend-line')
.selectAll('g.legend-entry')
.data(data);
// Enter
entries.enter()
.append('g')
.classed('legend-entry', true)
.attr('data-item', getId)
.attr('transform', function({name}) {
let horizontalOffset = xOffset,
lineHeight = chartHeight / 2,
verticalOffset = lineHeight,
labelWidth = textHelper.getTextWidth(name, textSize);
xOffset += markerSize + 2 * getLineElementMargin() + labelWidth;
return `translate(${horizontalOffset},${verticalOffset})`;
})
.merge(entries)
.append('circle')
.classed('legend-circle', true)
.attr('cx', markerSize/2)
.attr('cy', markerYOffset)
.attr('r', markerSize / 2)
.style('fill', getCircleFill)
.style('stroke-width', 1);
svg.select('.legend-group')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-name', true)
.text(getName)
.attr('x', getLineElementMargin())
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${textLetterSpacing}px`);
// Exit
svg.select('.legend-group')
.selectAll('g.legend-entry')
.exit()
.transition()
.style('opacity', 0)
.remove();
adjustLines();
} | javascript | function drawHorizontalLegend() {
let xOffset = markerSize;
svg.select('.legend-group')
.selectAll('g')
.remove();
// We want a single line
svg.select('.legend-group')
.append('g')
.classed('legend-line', true);
// And one entry per data item
entries = svg.select('.legend-line')
.selectAll('g.legend-entry')
.data(data);
// Enter
entries.enter()
.append('g')
.classed('legend-entry', true)
.attr('data-item', getId)
.attr('transform', function({name}) {
let horizontalOffset = xOffset,
lineHeight = chartHeight / 2,
verticalOffset = lineHeight,
labelWidth = textHelper.getTextWidth(name, textSize);
xOffset += markerSize + 2 * getLineElementMargin() + labelWidth;
return `translate(${horizontalOffset},${verticalOffset})`;
})
.merge(entries)
.append('circle')
.classed('legend-circle', true)
.attr('cx', markerSize/2)
.attr('cy', markerYOffset)
.attr('r', markerSize / 2)
.style('fill', getCircleFill)
.style('stroke-width', 1);
svg.select('.legend-group')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-name', true)
.text(getName)
.attr('x', getLineElementMargin())
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${textLetterSpacing}px`);
// Exit
svg.select('.legend-group')
.selectAll('g.legend-entry')
.exit()
.transition()
.style('opacity', 0)
.remove();
adjustLines();
} | [
"function",
"drawHorizontalLegend",
"(",
")",
"{",
"let",
"xOffset",
"=",
"markerSize",
";",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g'",
")",
".",
"remove",
"(",
")",
";",
"// We want a single line",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-line'",
",",
"true",
")",
";",
"// And one entry per data item",
"entries",
"=",
"svg",
".",
"select",
"(",
"'.legend-line'",
")",
".",
"selectAll",
"(",
"'g.legend-entry'",
")",
".",
"data",
"(",
"data",
")",
";",
"// Enter",
"entries",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-entry'",
",",
"true",
")",
".",
"attr",
"(",
"'data-item'",
",",
"getId",
")",
".",
"attr",
"(",
"'transform'",
",",
"function",
"(",
"{",
"name",
"}",
")",
"{",
"let",
"horizontalOffset",
"=",
"xOffset",
",",
"lineHeight",
"=",
"chartHeight",
"/",
"2",
",",
"verticalOffset",
"=",
"lineHeight",
",",
"labelWidth",
"=",
"textHelper",
".",
"getTextWidth",
"(",
"name",
",",
"textSize",
")",
";",
"xOffset",
"+=",
"markerSize",
"+",
"2",
"*",
"getLineElementMargin",
"(",
")",
"+",
"labelWidth",
";",
"return",
"`",
"${",
"horizontalOffset",
"}",
"${",
"verticalOffset",
"}",
"`",
";",
"}",
")",
".",
"merge",
"(",
"entries",
")",
".",
"append",
"(",
"'circle'",
")",
".",
"classed",
"(",
"'legend-circle'",
",",
"true",
")",
".",
"attr",
"(",
"'cx'",
",",
"markerSize",
"/",
"2",
")",
".",
"attr",
"(",
"'cy'",
",",
"markerYOffset",
")",
".",
"attr",
"(",
"'r'",
",",
"markerSize",
"/",
"2",
")",
".",
"style",
"(",
"'fill'",
",",
"getCircleFill",
")",
".",
"style",
"(",
"'stroke-width'",
",",
"1",
")",
";",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-entry'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"classed",
"(",
"'legend-entry-name'",
",",
"true",
")",
".",
"text",
"(",
"getName",
")",
".",
"attr",
"(",
"'x'",
",",
"getLineElementMargin",
"(",
")",
")",
".",
"style",
"(",
"'font-size'",
",",
"`",
"${",
"textSize",
"}",
"`",
")",
".",
"style",
"(",
"'letter-spacing'",
",",
"`",
"${",
"textLetterSpacing",
"}",
"`",
")",
";",
"// Exit",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-entry'",
")",
".",
"exit",
"(",
")",
".",
"transition",
"(",
")",
".",
"style",
"(",
"'opacity'",
",",
"0",
")",
".",
"remove",
"(",
")",
";",
"adjustLines",
"(",
")",
";",
"}"
] | Draws the entries of the legend within a single line
@private | [
"Draws",
"the",
"entries",
"of",
"the",
"legend",
"within",
"a",
"single",
"line"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L268-L327 |
8,518 | eventbrite/britecharts | src/charts/legend.js | drawVerticalLegend | function drawVerticalLegend() {
svg.select('.legend-group')
.selectAll('g')
.remove();
entries = svg.select('.legend-group')
.selectAll('g.legend-line')
.data(data);
// Enter
entries.enter()
.append('g')
.classed('legend-line', true)
.append('g')
.classed('legend-entry', true)
.attr('data-item', getId)
.attr('transform', function(d, i) {
let horizontalOffset = markerSize + getLineElementMargin(),
lineHeight = chartHeight/ (data.length + 1),
verticalOffset = (i + 1) * lineHeight;
return `translate(${horizontalOffset},${verticalOffset})`;
})
.merge(entries)
.append('circle')
.classed('legend-circle', true)
.attr('cx', markerSize/2)
.attr('cy', markerYOffset)
.attr('r', markerSize/2 )
.style('fill', getCircleFill)
.style('stroke-width', 1);
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-name', true)
.text(getName)
.attr('x', getLineElementMargin())
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${textLetterSpacing}px`);
if (hasQuantities) {
writeEntryValues();
} else {
centerVerticalLegendOnSVG();
}
// Exit
svg.select('.legend-group')
.selectAll('g.legend-line')
.exit()
.transition()
.style('opacity', 0)
.remove();
} | javascript | function drawVerticalLegend() {
svg.select('.legend-group')
.selectAll('g')
.remove();
entries = svg.select('.legend-group')
.selectAll('g.legend-line')
.data(data);
// Enter
entries.enter()
.append('g')
.classed('legend-line', true)
.append('g')
.classed('legend-entry', true)
.attr('data-item', getId)
.attr('transform', function(d, i) {
let horizontalOffset = markerSize + getLineElementMargin(),
lineHeight = chartHeight/ (data.length + 1),
verticalOffset = (i + 1) * lineHeight;
return `translate(${horizontalOffset},${verticalOffset})`;
})
.merge(entries)
.append('circle')
.classed('legend-circle', true)
.attr('cx', markerSize/2)
.attr('cy', markerYOffset)
.attr('r', markerSize/2 )
.style('fill', getCircleFill)
.style('stroke-width', 1);
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-name', true)
.text(getName)
.attr('x', getLineElementMargin())
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${textLetterSpacing}px`);
if (hasQuantities) {
writeEntryValues();
} else {
centerVerticalLegendOnSVG();
}
// Exit
svg.select('.legend-group')
.selectAll('g.legend-line')
.exit()
.transition()
.style('opacity', 0)
.remove();
} | [
"function",
"drawVerticalLegend",
"(",
")",
"{",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g'",
")",
".",
"remove",
"(",
")",
";",
"entries",
"=",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-line'",
")",
".",
"data",
"(",
"data",
")",
";",
"// Enter",
"entries",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-line'",
",",
"true",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-entry'",
",",
"true",
")",
".",
"attr",
"(",
"'data-item'",
",",
"getId",
")",
".",
"attr",
"(",
"'transform'",
",",
"function",
"(",
"d",
",",
"i",
")",
"{",
"let",
"horizontalOffset",
"=",
"markerSize",
"+",
"getLineElementMargin",
"(",
")",
",",
"lineHeight",
"=",
"chartHeight",
"/",
"(",
"data",
".",
"length",
"+",
"1",
")",
",",
"verticalOffset",
"=",
"(",
"i",
"+",
"1",
")",
"*",
"lineHeight",
";",
"return",
"`",
"${",
"horizontalOffset",
"}",
"${",
"verticalOffset",
"}",
"`",
";",
"}",
")",
".",
"merge",
"(",
"entries",
")",
".",
"append",
"(",
"'circle'",
")",
".",
"classed",
"(",
"'legend-circle'",
",",
"true",
")",
".",
"attr",
"(",
"'cx'",
",",
"markerSize",
"/",
"2",
")",
".",
"attr",
"(",
"'cy'",
",",
"markerYOffset",
")",
".",
"attr",
"(",
"'r'",
",",
"markerSize",
"/",
"2",
")",
".",
"style",
"(",
"'fill'",
",",
"getCircleFill",
")",
".",
"style",
"(",
"'stroke-width'",
",",
"1",
")",
";",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-line'",
")",
".",
"selectAll",
"(",
"'g.legend-entry'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"classed",
"(",
"'legend-entry-name'",
",",
"true",
")",
".",
"text",
"(",
"getName",
")",
".",
"attr",
"(",
"'x'",
",",
"getLineElementMargin",
"(",
")",
")",
".",
"style",
"(",
"'font-size'",
",",
"`",
"${",
"textSize",
"}",
"`",
")",
".",
"style",
"(",
"'letter-spacing'",
",",
"`",
"${",
"textLetterSpacing",
"}",
"`",
")",
";",
"if",
"(",
"hasQuantities",
")",
"{",
"writeEntryValues",
"(",
")",
";",
"}",
"else",
"{",
"centerVerticalLegendOnSVG",
"(",
")",
";",
"}",
"// Exit",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-line'",
")",
".",
"exit",
"(",
")",
".",
"transition",
"(",
")",
".",
"style",
"(",
"'opacity'",
",",
"0",
")",
".",
"remove",
"(",
")",
";",
"}"
] | Draws the entries of the legend
@private | [
"Draws",
"the",
"entries",
"of",
"the",
"legend"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L333-L388 |
8,519 | eventbrite/britecharts | src/charts/legend.js | fadeLinesBut | function fadeLinesBut(exceptionItemId) {
let classToFade = 'g.legend-entry';
let entryLine = svg.select(`[data-item="${exceptionItemId}"]`);
if (entryLine.nodes().length){
svg.select('.legend-group')
.selectAll(classToFade)
.classed(isFadedClassName, true);
entryLine.classed(isFadedClassName, false);
}
} | javascript | function fadeLinesBut(exceptionItemId) {
let classToFade = 'g.legend-entry';
let entryLine = svg.select(`[data-item="${exceptionItemId}"]`);
if (entryLine.nodes().length){
svg.select('.legend-group')
.selectAll(classToFade)
.classed(isFadedClassName, true);
entryLine.classed(isFadedClassName, false);
}
} | [
"function",
"fadeLinesBut",
"(",
"exceptionItemId",
")",
"{",
"let",
"classToFade",
"=",
"'g.legend-entry'",
";",
"let",
"entryLine",
"=",
"svg",
".",
"select",
"(",
"`",
"${",
"exceptionItemId",
"}",
"`",
")",
";",
"if",
"(",
"entryLine",
".",
"nodes",
"(",
")",
".",
"length",
")",
"{",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"classToFade",
")",
".",
"classed",
"(",
"isFadedClassName",
",",
"true",
")",
";",
"entryLine",
".",
"classed",
"(",
"isFadedClassName",
",",
"false",
")",
";",
"}",
"}"
] | Applies the faded class to all lines but the one that has the given id
@param {number} exceptionItemId Id of the line that needs to stay the same
@private | [
"Applies",
"the",
"faded",
"class",
"to",
"all",
"lines",
"but",
"the",
"one",
"that",
"has",
"the",
"given",
"id"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L395-L406 |
8,520 | eventbrite/britecharts | src/charts/legend.js | splitInLines | function splitInLines() {
let legendEntries = svg.selectAll('.legend-entry');
let numberOfEntries = legendEntries.size();
let lineHeight = (chartHeight / 2) * 1.7;
let newLine = svg.select('.legend-group')
.append('g')
.classed('legend-line', true)
.attr('transform', `translate(0, ${lineHeight})`);
let lastEntry = legendEntries.filter(`:nth-child(${numberOfEntries})`);
lastEntry.attr('transform', `translate(${markerSize},0)`);
newLine.append(() => lastEntry.node());
} | javascript | function splitInLines() {
let legendEntries = svg.selectAll('.legend-entry');
let numberOfEntries = legendEntries.size();
let lineHeight = (chartHeight / 2) * 1.7;
let newLine = svg.select('.legend-group')
.append('g')
.classed('legend-line', true)
.attr('transform', `translate(0, ${lineHeight})`);
let lastEntry = legendEntries.filter(`:nth-child(${numberOfEntries})`);
lastEntry.attr('transform', `translate(${markerSize},0)`);
newLine.append(() => lastEntry.node());
} | [
"function",
"splitInLines",
"(",
")",
"{",
"let",
"legendEntries",
"=",
"svg",
".",
"selectAll",
"(",
"'.legend-entry'",
")",
";",
"let",
"numberOfEntries",
"=",
"legendEntries",
".",
"size",
"(",
")",
";",
"let",
"lineHeight",
"=",
"(",
"chartHeight",
"/",
"2",
")",
"*",
"1.7",
";",
"let",
"newLine",
"=",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-line'",
",",
"true",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"lineHeight",
"}",
"`",
")",
";",
"let",
"lastEntry",
"=",
"legendEntries",
".",
"filter",
"(",
"`",
"${",
"numberOfEntries",
"}",
"`",
")",
";",
"lastEntry",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"markerSize",
"}",
"`",
")",
";",
"newLine",
".",
"append",
"(",
"(",
")",
"=>",
"lastEntry",
".",
"node",
"(",
")",
")",
";",
"}"
] | Simple method to move the last item of an overflowing legend into the next line
@return {void}
@private | [
"Simple",
"method",
"to",
"move",
"the",
"last",
"item",
"of",
"an",
"overflowing",
"legend",
"into",
"the",
"next",
"line"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L422-L434 |
8,521 | eventbrite/britecharts | src/charts/legend.js | writeEntryValues | function writeEntryValues() {
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-value', true)
.text(getFormattedQuantity)
.attr('x', chartWidth - valueReservedSpace)
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${numberLetterSpacing}px`)
.style('text-anchor', 'end')
.style('startOffset', '100%');
} | javascript | function writeEntryValues() {
svg.select('.legend-group')
.selectAll('g.legend-line')
.selectAll('g.legend-entry')
.append('text')
.classed('legend-entry-value', true)
.text(getFormattedQuantity)
.attr('x', chartWidth - valueReservedSpace)
.style('font-size', `${textSize}px`)
.style('letter-spacing', `${numberLetterSpacing}px`)
.style('text-anchor', 'end')
.style('startOffset', '100%');
} | [
"function",
"writeEntryValues",
"(",
")",
"{",
"svg",
".",
"select",
"(",
"'.legend-group'",
")",
".",
"selectAll",
"(",
"'g.legend-line'",
")",
".",
"selectAll",
"(",
"'g.legend-entry'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"classed",
"(",
"'legend-entry-value'",
",",
"true",
")",
".",
"text",
"(",
"getFormattedQuantity",
")",
".",
"attr",
"(",
"'x'",
",",
"chartWidth",
"-",
"valueReservedSpace",
")",
".",
"style",
"(",
"'font-size'",
",",
"`",
"${",
"textSize",
"}",
"`",
")",
".",
"style",
"(",
"'letter-spacing'",
",",
"`",
"${",
"numberLetterSpacing",
"}",
"`",
")",
".",
"style",
"(",
"'text-anchor'",
",",
"'end'",
")",
".",
"style",
"(",
"'startOffset'",
",",
"'100%'",
")",
";",
"}"
] | Draws the data entry quantities within the legend-entry lines
@return {void}
@private | [
"Draws",
"the",
"data",
"entry",
"quantities",
"within",
"the",
"legend",
"-",
"entry",
"lines"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/legend.js#L441-L453 |
8,522 | eventbrite/britecharts | src/charts/line.js | cleanData | function cleanData({dataByTopic, dataByDate, data}) {
if (!dataByTopic && !data) {
throw new Error('Data needs to have a dataByTopic or data property. See more in http://eventbrite.github.io/britecharts/global.html#LineChartData__anchor');
}
// If dataByTopic or data are not present, we generate them
if (!dataByTopic) {
dataByTopic = d3Collection.nest()
.key(getVariableTopicName)
.entries(data)
.map(d => ({
topic: d.values[0]['name'],
topicName: d.key,
dates: d.values
})
);
} else {
data = dataByTopic.reduce((accum, topic) => {
topic.dates.forEach((date) => {
accum.push({
topicName: topic[topicNameLabel],
name: topic[topicLabel],
date: date[dateLabel],
value: date[valueLabel]
});
});
return accum;
}, []);
}
// Nest data by date and format
dataByDate = d3Collection.nest()
.key(getDate)
.entries(data)
.map((d) => {
return {
date: new Date(d.key),
topics: d.values
}
});
const normalizedDataByTopic = dataByTopic.reduce((accum, topic) => {
let {dates, ...restProps} = topic;
let newDates = dates.map(d => ({
date: new Date(d[dateLabel]),
value: +d[valueLabel]
}));
accum.push({ dates: newDates, ...restProps });
return accum;
}, []);
return {
dataByTopic: normalizedDataByTopic,
dataByDate
};
} | javascript | function cleanData({dataByTopic, dataByDate, data}) {
if (!dataByTopic && !data) {
throw new Error('Data needs to have a dataByTopic or data property. See more in http://eventbrite.github.io/britecharts/global.html#LineChartData__anchor');
}
// If dataByTopic or data are not present, we generate them
if (!dataByTopic) {
dataByTopic = d3Collection.nest()
.key(getVariableTopicName)
.entries(data)
.map(d => ({
topic: d.values[0]['name'],
topicName: d.key,
dates: d.values
})
);
} else {
data = dataByTopic.reduce((accum, topic) => {
topic.dates.forEach((date) => {
accum.push({
topicName: topic[topicNameLabel],
name: topic[topicLabel],
date: date[dateLabel],
value: date[valueLabel]
});
});
return accum;
}, []);
}
// Nest data by date and format
dataByDate = d3Collection.nest()
.key(getDate)
.entries(data)
.map((d) => {
return {
date: new Date(d.key),
topics: d.values
}
});
const normalizedDataByTopic = dataByTopic.reduce((accum, topic) => {
let {dates, ...restProps} = topic;
let newDates = dates.map(d => ({
date: new Date(d[dateLabel]),
value: +d[valueLabel]
}));
accum.push({ dates: newDates, ...restProps });
return accum;
}, []);
return {
dataByTopic: normalizedDataByTopic,
dataByDate
};
} | [
"function",
"cleanData",
"(",
"{",
"dataByTopic",
",",
"dataByDate",
",",
"data",
"}",
")",
"{",
"if",
"(",
"!",
"dataByTopic",
"&&",
"!",
"data",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Data needs to have a dataByTopic or data property. See more in http://eventbrite.github.io/britecharts/global.html#LineChartData__anchor'",
")",
";",
"}",
"// If dataByTopic or data are not present, we generate them",
"if",
"(",
"!",
"dataByTopic",
")",
"{",
"dataByTopic",
"=",
"d3Collection",
".",
"nest",
"(",
")",
".",
"key",
"(",
"getVariableTopicName",
")",
".",
"entries",
"(",
"data",
")",
".",
"map",
"(",
"d",
"=>",
"(",
"{",
"topic",
":",
"d",
".",
"values",
"[",
"0",
"]",
"[",
"'name'",
"]",
",",
"topicName",
":",
"d",
".",
"key",
",",
"dates",
":",
"d",
".",
"values",
"}",
")",
")",
";",
"}",
"else",
"{",
"data",
"=",
"dataByTopic",
".",
"reduce",
"(",
"(",
"accum",
",",
"topic",
")",
"=>",
"{",
"topic",
".",
"dates",
".",
"forEach",
"(",
"(",
"date",
")",
"=>",
"{",
"accum",
".",
"push",
"(",
"{",
"topicName",
":",
"topic",
"[",
"topicNameLabel",
"]",
",",
"name",
":",
"topic",
"[",
"topicLabel",
"]",
",",
"date",
":",
"date",
"[",
"dateLabel",
"]",
",",
"value",
":",
"date",
"[",
"valueLabel",
"]",
"}",
")",
";",
"}",
")",
";",
"return",
"accum",
";",
"}",
",",
"[",
"]",
")",
";",
"}",
"// Nest data by date and format",
"dataByDate",
"=",
"d3Collection",
".",
"nest",
"(",
")",
".",
"key",
"(",
"getDate",
")",
".",
"entries",
"(",
"data",
")",
".",
"map",
"(",
"(",
"d",
")",
"=>",
"{",
"return",
"{",
"date",
":",
"new",
"Date",
"(",
"d",
".",
"key",
")",
",",
"topics",
":",
"d",
".",
"values",
"}",
"}",
")",
";",
"const",
"normalizedDataByTopic",
"=",
"dataByTopic",
".",
"reduce",
"(",
"(",
"accum",
",",
"topic",
")",
"=>",
"{",
"let",
"{",
"dates",
",",
"...",
"restProps",
"}",
"=",
"topic",
";",
"let",
"newDates",
"=",
"dates",
".",
"map",
"(",
"d",
"=>",
"(",
"{",
"date",
":",
"new",
"Date",
"(",
"d",
"[",
"dateLabel",
"]",
")",
",",
"value",
":",
"+",
"d",
"[",
"valueLabel",
"]",
"}",
")",
")",
";",
"accum",
".",
"push",
"(",
"{",
"dates",
":",
"newDates",
",",
"...",
"restProps",
"}",
")",
";",
"return",
"accum",
";",
"}",
",",
"[",
"]",
")",
";",
"return",
"{",
"dataByTopic",
":",
"normalizedDataByTopic",
",",
"dataByDate",
"}",
";",
"}"
] | Parses dates and values into JS Date objects and numbers
@param {obj} dataByTopic Raw data grouped by topic
@return {obj} Parsed data with dataByTopic and dataByDate | [
"Parses",
"dates",
"and",
"values",
"into",
"JS",
"Date",
"objects",
"and",
"numbers"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L548-L607 |
8,523 | eventbrite/britecharts | src/charts/line.js | drawAxis | function drawAxis(){
svg.select('.x-axis-group .axis.x')
.attr('transform', `translate(0, ${chartHeight})`)
.call(xAxis);
if (xAxisFormat !== 'custom') {
svg.select('.x-axis-group .month-axis')
.attr('transform', `translate(0, ${(chartHeight + monthAxisPadding)})`)
.call(xMonthAxis);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
svg.selectAll('.x-axis-label').remove();
}
let xLabelXPosition = chartWidth/2;
let xLabelYPosition = chartHeight + monthAxisPadding + xAxisLabelPadding;
xAxisLabelEl = svg.select('.x-axis-group')
.append('text')
.attr('x', xLabelXPosition)
.attr('y', xLabelYPosition)
.attr('text-anchor', 'middle')
.attr('class', 'x-axis-label')
.text(xAxisLabel);
}
svg.select('.y-axis-group .axis.y')
.attr('transform', `translate(${-xAxisPadding.left}, 0)`)
.call(yAxis)
.call(adjustYTickLabels);
if (yAxisLabel) {
if (yAxisLabelEl) {
svg.selectAll('.y-axis-label').remove();
}
// Note this coordinates are rotated, so they are not what they look
let yLabelYPosition = -yAxisLabelPadding - xAxisPadding.left;
let yLabelXPosition = -chartHeight/2;
yAxisLabelEl = svg.select('.y-axis-group')
.append('text')
.attr('x', yLabelXPosition)
.attr('y', yLabelYPosition)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270)')
.attr('class', 'y-axis-label')
.text(yAxisLabel);
}
} | javascript | function drawAxis(){
svg.select('.x-axis-group .axis.x')
.attr('transform', `translate(0, ${chartHeight})`)
.call(xAxis);
if (xAxisFormat !== 'custom') {
svg.select('.x-axis-group .month-axis')
.attr('transform', `translate(0, ${(chartHeight + monthAxisPadding)})`)
.call(xMonthAxis);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
svg.selectAll('.x-axis-label').remove();
}
let xLabelXPosition = chartWidth/2;
let xLabelYPosition = chartHeight + monthAxisPadding + xAxisLabelPadding;
xAxisLabelEl = svg.select('.x-axis-group')
.append('text')
.attr('x', xLabelXPosition)
.attr('y', xLabelYPosition)
.attr('text-anchor', 'middle')
.attr('class', 'x-axis-label')
.text(xAxisLabel);
}
svg.select('.y-axis-group .axis.y')
.attr('transform', `translate(${-xAxisPadding.left}, 0)`)
.call(yAxis)
.call(adjustYTickLabels);
if (yAxisLabel) {
if (yAxisLabelEl) {
svg.selectAll('.y-axis-label').remove();
}
// Note this coordinates are rotated, so they are not what they look
let yLabelYPosition = -yAxisLabelPadding - xAxisPadding.left;
let yLabelXPosition = -chartHeight/2;
yAxisLabelEl = svg.select('.y-axis-group')
.append('text')
.attr('x', yLabelXPosition)
.attr('y', yLabelYPosition)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270)')
.attr('class', 'y-axis-label')
.text(yAxisLabel);
}
} | [
"function",
"drawAxis",
"(",
")",
"{",
"svg",
".",
"select",
"(",
"'.x-axis-group .axis.x'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"chartHeight",
"}",
"`",
")",
".",
"call",
"(",
"xAxis",
")",
";",
"if",
"(",
"xAxisFormat",
"!==",
"'custom'",
")",
"{",
"svg",
".",
"select",
"(",
"'.x-axis-group .month-axis'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"(",
"chartHeight",
"+",
"monthAxisPadding",
")",
"}",
"`",
")",
".",
"call",
"(",
"xMonthAxis",
")",
";",
"}",
"if",
"(",
"xAxisLabel",
")",
"{",
"if",
"(",
"xAxisLabelEl",
")",
"{",
"svg",
".",
"selectAll",
"(",
"'.x-axis-label'",
")",
".",
"remove",
"(",
")",
";",
"}",
"let",
"xLabelXPosition",
"=",
"chartWidth",
"/",
"2",
";",
"let",
"xLabelYPosition",
"=",
"chartHeight",
"+",
"monthAxisPadding",
"+",
"xAxisLabelPadding",
";",
"xAxisLabelEl",
"=",
"svg",
".",
"select",
"(",
"'.x-axis-group'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"attr",
"(",
"'x'",
",",
"xLabelXPosition",
")",
".",
"attr",
"(",
"'y'",
",",
"xLabelYPosition",
")",
".",
"attr",
"(",
"'text-anchor'",
",",
"'middle'",
")",
".",
"attr",
"(",
"'class'",
",",
"'x-axis-label'",
")",
".",
"text",
"(",
"xAxisLabel",
")",
";",
"}",
"svg",
".",
"select",
"(",
"'.y-axis-group .axis.y'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"-",
"xAxisPadding",
".",
"left",
"}",
"`",
")",
".",
"call",
"(",
"yAxis",
")",
".",
"call",
"(",
"adjustYTickLabels",
")",
";",
"if",
"(",
"yAxisLabel",
")",
"{",
"if",
"(",
"yAxisLabelEl",
")",
"{",
"svg",
".",
"selectAll",
"(",
"'.y-axis-label'",
")",
".",
"remove",
"(",
")",
";",
"}",
"// Note this coordinates are rotated, so they are not what they look",
"let",
"yLabelYPosition",
"=",
"-",
"yAxisLabelPadding",
"-",
"xAxisPadding",
".",
"left",
";",
"let",
"yLabelXPosition",
"=",
"-",
"chartHeight",
"/",
"2",
";",
"yAxisLabelEl",
"=",
"svg",
".",
"select",
"(",
"'.y-axis-group'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"attr",
"(",
"'x'",
",",
"yLabelXPosition",
")",
".",
"attr",
"(",
"'y'",
",",
"yLabelYPosition",
")",
".",
"attr",
"(",
"'text-anchor'",
",",
"'middle'",
")",
".",
"attr",
"(",
"'transform'",
",",
"'rotate(270)'",
")",
".",
"attr",
"(",
"'class'",
",",
"'y-axis-label'",
")",
".",
"text",
"(",
"yAxisLabel",
")",
";",
"}",
"}"
] | Draws the x and y axis on the svg object within their
respective groups along with the axis labels if given
@private | [
"Draws",
"the",
"x",
"and",
"y",
"axis",
"on",
"the",
"svg",
"object",
"within",
"their",
"respective",
"groups",
"along",
"with",
"the",
"axis",
"labels",
"if",
"given"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L646-L695 |
8,524 | eventbrite/britecharts | src/charts/line.js | drawLines | function drawLines(){
let lines,
topicLine;
topicLine = d3Shape.line()
.curve(curveMap[lineCurve])
.x(({date}) => xScale(date))
.y(({value}) => yScale(value));
lines = svg.select('.chart-group').selectAll('.line')
.data(dataByTopic, getTopic);
paths = lines.enter()
.append('g')
.attr('class', 'topic')
.append('path')
.attr('class', 'line')
.merge(lines)
.attr('id', ({topic}) => topic)
.attr('d', ({dates}) => topicLine(dates))
.style('stroke', (d) => (
dataByTopic.length === 1 ? `url(#${lineGradientId})` : getLineColor(d)
));
lines
.exit()
.remove();
} | javascript | function drawLines(){
let lines,
topicLine;
topicLine = d3Shape.line()
.curve(curveMap[lineCurve])
.x(({date}) => xScale(date))
.y(({value}) => yScale(value));
lines = svg.select('.chart-group').selectAll('.line')
.data(dataByTopic, getTopic);
paths = lines.enter()
.append('g')
.attr('class', 'topic')
.append('path')
.attr('class', 'line')
.merge(lines)
.attr('id', ({topic}) => topic)
.attr('d', ({dates}) => topicLine(dates))
.style('stroke', (d) => (
dataByTopic.length === 1 ? `url(#${lineGradientId})` : getLineColor(d)
));
lines
.exit()
.remove();
} | [
"function",
"drawLines",
"(",
")",
"{",
"let",
"lines",
",",
"topicLine",
";",
"topicLine",
"=",
"d3Shape",
".",
"line",
"(",
")",
".",
"curve",
"(",
"curveMap",
"[",
"lineCurve",
"]",
")",
".",
"x",
"(",
"(",
"{",
"date",
"}",
")",
"=>",
"xScale",
"(",
"date",
")",
")",
".",
"y",
"(",
"(",
"{",
"value",
"}",
")",
"=>",
"yScale",
"(",
"value",
")",
")",
";",
"lines",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'.line'",
")",
".",
"data",
"(",
"dataByTopic",
",",
"getTopic",
")",
";",
"paths",
"=",
"lines",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'g'",
")",
".",
"attr",
"(",
"'class'",
",",
"'topic'",
")",
".",
"append",
"(",
"'path'",
")",
".",
"attr",
"(",
"'class'",
",",
"'line'",
")",
".",
"merge",
"(",
"lines",
")",
".",
"attr",
"(",
"'id'",
",",
"(",
"{",
"topic",
"}",
")",
"=>",
"topic",
")",
".",
"attr",
"(",
"'d'",
",",
"(",
"{",
"dates",
"}",
")",
"=>",
"topicLine",
"(",
"dates",
")",
")",
".",
"style",
"(",
"'stroke'",
",",
"(",
"d",
")",
"=>",
"(",
"dataByTopic",
".",
"length",
"===",
"1",
"?",
"`",
"${",
"lineGradientId",
"}",
"`",
":",
"getLineColor",
"(",
"d",
")",
")",
")",
";",
"lines",
".",
"exit",
"(",
")",
".",
"remove",
"(",
")",
";",
"}"
] | Draws the line elements within the chart group
@private | [
"Draws",
"the",
"line",
"elements",
"within",
"the",
"chart",
"group"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L701-L728 |
8,525 | eventbrite/britecharts | src/charts/line.js | drawAllDataPoints | function drawAllDataPoints() {
svg.select('.chart-group')
.selectAll('.data-points-container')
.remove();
const nodesById = paths.nodes().reduce((acc, node) => {
acc[node.id] = node
return acc;
}, {});
const allTopics = dataByDate.reduce((accum, dataPoint) => {
const dataPointTopics = dataPoint.topics.map(topic => ({
topic,
node: nodesById[topic.name]
}));
accum = [...accum, ...dataPointTopics];
return accum;
}, []);
let allDataPoints = svg.select('.chart-group')
.append('g')
.classed('data-points-container', true)
.selectAll('circle')
.data(allTopics)
.enter()
.append('circle')
.classed('data-point-mark', true)
.attr('r', highlightCircleRadius)
.style('stroke-width', highlightCircleStroke)
.style('stroke', (d) => topicColorMap[d.topic.name])
.style('cursor', 'pointer')
.attr('cx', d => xScale(new Date(d.topic.date)))
.attr('cy', d => getPathYFromX(xScale(new Date(d.topic.date)), d.node, d.topic.name));
} | javascript | function drawAllDataPoints() {
svg.select('.chart-group')
.selectAll('.data-points-container')
.remove();
const nodesById = paths.nodes().reduce((acc, node) => {
acc[node.id] = node
return acc;
}, {});
const allTopics = dataByDate.reduce((accum, dataPoint) => {
const dataPointTopics = dataPoint.topics.map(topic => ({
topic,
node: nodesById[topic.name]
}));
accum = [...accum, ...dataPointTopics];
return accum;
}, []);
let allDataPoints = svg.select('.chart-group')
.append('g')
.classed('data-points-container', true)
.selectAll('circle')
.data(allTopics)
.enter()
.append('circle')
.classed('data-point-mark', true)
.attr('r', highlightCircleRadius)
.style('stroke-width', highlightCircleStroke)
.style('stroke', (d) => topicColorMap[d.topic.name])
.style('cursor', 'pointer')
.attr('cx', d => xScale(new Date(d.topic.date)))
.attr('cy', d => getPathYFromX(xScale(new Date(d.topic.date)), d.node, d.topic.name));
} | [
"function",
"drawAllDataPoints",
"(",
")",
"{",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'.data-points-container'",
")",
".",
"remove",
"(",
")",
";",
"const",
"nodesById",
"=",
"paths",
".",
"nodes",
"(",
")",
".",
"reduce",
"(",
"(",
"acc",
",",
"node",
")",
"=>",
"{",
"acc",
"[",
"node",
".",
"id",
"]",
"=",
"node",
"return",
"acc",
";",
"}",
",",
"{",
"}",
")",
";",
"const",
"allTopics",
"=",
"dataByDate",
".",
"reduce",
"(",
"(",
"accum",
",",
"dataPoint",
")",
"=>",
"{",
"const",
"dataPointTopics",
"=",
"dataPoint",
".",
"topics",
".",
"map",
"(",
"topic",
"=>",
"(",
"{",
"topic",
",",
"node",
":",
"nodesById",
"[",
"topic",
".",
"name",
"]",
"}",
")",
")",
";",
"accum",
"=",
"[",
"...",
"accum",
",",
"...",
"dataPointTopics",
"]",
";",
"return",
"accum",
";",
"}",
",",
"[",
"]",
")",
";",
"let",
"allDataPoints",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'data-points-container'",
",",
"true",
")",
".",
"selectAll",
"(",
"'circle'",
")",
".",
"data",
"(",
"allTopics",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'circle'",
")",
".",
"classed",
"(",
"'data-point-mark'",
",",
"true",
")",
".",
"attr",
"(",
"'r'",
",",
"highlightCircleRadius",
")",
".",
"style",
"(",
"'stroke-width'",
",",
"highlightCircleStroke",
")",
".",
"style",
"(",
"'stroke'",
",",
"(",
"d",
")",
"=>",
"topicColorMap",
"[",
"d",
".",
"topic",
".",
"name",
"]",
")",
".",
"style",
"(",
"'cursor'",
",",
"'pointer'",
")",
".",
"attr",
"(",
"'cx'",
",",
"d",
"=>",
"xScale",
"(",
"new",
"Date",
"(",
"d",
".",
"topic",
".",
"date",
")",
")",
")",
".",
"attr",
"(",
"'cy'",
",",
"d",
"=>",
"getPathYFromX",
"(",
"xScale",
"(",
"new",
"Date",
"(",
"d",
".",
"topic",
".",
"date",
")",
")",
",",
"d",
".",
"node",
",",
"d",
".",
"topic",
".",
"name",
")",
")",
";",
"}"
] | Draws all data points of the chart
if shouldShowAllDataPoints is set to true
@private
@return void | [
"Draws",
"all",
"data",
"points",
"of",
"the",
"chart",
"if",
"shouldShowAllDataPoints",
"is",
"set",
"to",
"true"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L803-L840 |
8,526 | eventbrite/britecharts | src/charts/line.js | findOutNearestDate | function findOutNearestDate(x0, d0, d1){
return (new Date(x0).getTime() - new Date(d0.date).getTime()) > (new Date(d1.date).getTime() - new Date(x0).getTime()) ? d0 : d1;
} | javascript | function findOutNearestDate(x0, d0, d1){
return (new Date(x0).getTime() - new Date(d0.date).getTime()) > (new Date(d1.date).getTime() - new Date(x0).getTime()) ? d0 : d1;
} | [
"function",
"findOutNearestDate",
"(",
"x0",
",",
"d0",
",",
"d1",
")",
"{",
"return",
"(",
"new",
"Date",
"(",
"x0",
")",
".",
"getTime",
"(",
")",
"-",
"new",
"Date",
"(",
"d0",
".",
"date",
")",
".",
"getTime",
"(",
")",
")",
">",
"(",
"new",
"Date",
"(",
"d1",
".",
"date",
")",
".",
"getTime",
"(",
")",
"-",
"new",
"Date",
"(",
"x0",
")",
".",
"getTime",
"(",
")",
")",
"?",
"d0",
":",
"d1",
";",
"}"
] | Finds out which datapoint is closer to the given x position
@param {Number} x0 Date value for data point
@param {Object} d0 Previous datapoint
@param {Object} d1 Next datapoint
@return {Object} d0 or d1, the datapoint with closest date to x0 | [
"Finds",
"out",
"which",
"datapoint",
"is",
"closer",
"to",
"the",
"given",
"x",
"position"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L877-L879 |
8,527 | eventbrite/britecharts | src/charts/line.js | getPathYFromX | function getPathYFromX(x, path, name, error) {
const key = `${name}-${x}`;
if (key in pathYCache) {
return pathYCache[key];
}
error = error || 0.01;
const maxIterations = 100;
let lengthStart = 0;
let lengthEnd = path.getTotalLength();
let point = path.getPointAtLength((lengthEnd + lengthStart) / 2);
let iterations = 0;
while (x < point.x - error || x > point.x + error) {
const midpoint = (lengthStart + lengthEnd) / 2;
point = path.getPointAtLength(midpoint);
if (x < point.x) {
lengthEnd = midpoint;
} else {
lengthStart = midpoint;
}
iterations += 1;
if (maxIterations < iterations) {
break;
}
}
pathYCache[key] = point.y
return pathYCache[key]
} | javascript | function getPathYFromX(x, path, name, error) {
const key = `${name}-${x}`;
if (key in pathYCache) {
return pathYCache[key];
}
error = error || 0.01;
const maxIterations = 100;
let lengthStart = 0;
let lengthEnd = path.getTotalLength();
let point = path.getPointAtLength((lengthEnd + lengthStart) / 2);
let iterations = 0;
while (x < point.x - error || x > point.x + error) {
const midpoint = (lengthStart + lengthEnd) / 2;
point = path.getPointAtLength(midpoint);
if (x < point.x) {
lengthEnd = midpoint;
} else {
lengthStart = midpoint;
}
iterations += 1;
if (maxIterations < iterations) {
break;
}
}
pathYCache[key] = point.y
return pathYCache[key]
} | [
"function",
"getPathYFromX",
"(",
"x",
",",
"path",
",",
"name",
",",
"error",
")",
"{",
"const",
"key",
"=",
"`",
"${",
"name",
"}",
"${",
"x",
"}",
"`",
";",
"if",
"(",
"key",
"in",
"pathYCache",
")",
"{",
"return",
"pathYCache",
"[",
"key",
"]",
";",
"}",
"error",
"=",
"error",
"||",
"0.01",
";",
"const",
"maxIterations",
"=",
"100",
";",
"let",
"lengthStart",
"=",
"0",
";",
"let",
"lengthEnd",
"=",
"path",
".",
"getTotalLength",
"(",
")",
";",
"let",
"point",
"=",
"path",
".",
"getPointAtLength",
"(",
"(",
"lengthEnd",
"+",
"lengthStart",
")",
"/",
"2",
")",
";",
"let",
"iterations",
"=",
"0",
";",
"while",
"(",
"x",
"<",
"point",
".",
"x",
"-",
"error",
"||",
"x",
">",
"point",
".",
"x",
"+",
"error",
")",
"{",
"const",
"midpoint",
"=",
"(",
"lengthStart",
"+",
"lengthEnd",
")",
"/",
"2",
";",
"point",
"=",
"path",
".",
"getPointAtLength",
"(",
"midpoint",
")",
";",
"if",
"(",
"x",
"<",
"point",
".",
"x",
")",
"{",
"lengthEnd",
"=",
"midpoint",
";",
"}",
"else",
"{",
"lengthStart",
"=",
"midpoint",
";",
"}",
"iterations",
"+=",
"1",
";",
"if",
"(",
"maxIterations",
"<",
"iterations",
")",
"{",
"break",
";",
"}",
"}",
"pathYCache",
"[",
"key",
"]",
"=",
"point",
".",
"y",
"return",
"pathYCache",
"[",
"key",
"]",
"}"
] | Finds the y coordinate of a path given an x coordinate and the line's path node.
@param {number} x The x coordinate
@param {node} path The path node element
@param {*} name - The name identifier of the topic
@param {number} error The margin of error from the actual x coordinate. Default 0.01
@private | [
"Finds",
"the",
"y",
"coordinate",
"of",
"a",
"path",
"given",
"an",
"x",
"coordinate",
"and",
"the",
"line",
"s",
"path",
"node",
"."
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/line.js#L1033-L1069 |
8,528 | eventbrite/britecharts | src/charts/bullet.js | buildContainerGroups | function buildContainerGroups() {
let container = svg
.append('g')
.classed('container-group', true)
.attr('transform', `translate(${margin.left}, ${margin.top})`);
container
.append('g').classed('grid-lines-group', true);
container
.append('g').classed('chart-group', true);
container
.append('g').classed('axis-group', true);
container
.append('g').classed('metadata-group', true);
if (hasTitle()) {
container.selectAll('.chart-group')
.attr('transform', `translate(${legendSpacing}, 0)`);
}
} | javascript | function buildContainerGroups() {
let container = svg
.append('g')
.classed('container-group', true)
.attr('transform', `translate(${margin.left}, ${margin.top})`);
container
.append('g').classed('grid-lines-group', true);
container
.append('g').classed('chart-group', true);
container
.append('g').classed('axis-group', true);
container
.append('g').classed('metadata-group', true);
if (hasTitle()) {
container.selectAll('.chart-group')
.attr('transform', `translate(${legendSpacing}, 0)`);
}
} | [
"function",
"buildContainerGroups",
"(",
")",
"{",
"let",
"container",
"=",
"svg",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'container-group'",
",",
"true",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"margin",
".",
"left",
"}",
"${",
"margin",
".",
"top",
"}",
"`",
")",
";",
"container",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'grid-lines-group'",
",",
"true",
")",
";",
"container",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'chart-group'",
",",
"true",
")",
";",
"container",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'axis-group'",
",",
"true",
")",
";",
"container",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'metadata-group'",
",",
"true",
")",
";",
"if",
"(",
"hasTitle",
"(",
")",
")",
"{",
"container",
".",
"selectAll",
"(",
"'.chart-group'",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"legendSpacing",
"}",
"`",
")",
";",
"}",
"}"
] | Builds containers for the chart, the axis and a wrapper for all of them
Also applies the Margin convention
@return {void}
@private | [
"Builds",
"containers",
"for",
"the",
"chart",
"the",
"axis",
"and",
"a",
"wrapper",
"for",
"all",
"of",
"them",
"Also",
"applies",
"the",
"Margin",
"convention"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L160-L179 |
8,529 | eventbrite/britecharts | src/charts/bullet.js | buildScales | function buildScales() {
const decidedRange = isReverse ? [chartWidth, 0] : [0, chartWidth];
xScale = d3Scale.scaleLinear()
.domain([0, Math.max(ranges[0], markers[0], measures[0])])
.rangeRound(decidedRange)
.nice();
// Derive width scales from x scales
barWidth = bulletWidth(xScale);
// set up opacity scale based on ranges and measures
rangeOpacityScale = ranges.map((d, i) => startMaxRangeOpacity - (i * rangeOpacifyDiff)).reverse();
measureOpacityScale = ranges.map((d, i) => 0.9 - (i * measureOpacifyDiff)).reverse();
// initialize range and measure bars and marker line colors
rangeColor = colorSchema[0];
measureColor = colorSchema[1];
} | javascript | function buildScales() {
const decidedRange = isReverse ? [chartWidth, 0] : [0, chartWidth];
xScale = d3Scale.scaleLinear()
.domain([0, Math.max(ranges[0], markers[0], measures[0])])
.rangeRound(decidedRange)
.nice();
// Derive width scales from x scales
barWidth = bulletWidth(xScale);
// set up opacity scale based on ranges and measures
rangeOpacityScale = ranges.map((d, i) => startMaxRangeOpacity - (i * rangeOpacifyDiff)).reverse();
measureOpacityScale = ranges.map((d, i) => 0.9 - (i * measureOpacifyDiff)).reverse();
// initialize range and measure bars and marker line colors
rangeColor = colorSchema[0];
measureColor = colorSchema[1];
} | [
"function",
"buildScales",
"(",
")",
"{",
"const",
"decidedRange",
"=",
"isReverse",
"?",
"[",
"chartWidth",
",",
"0",
"]",
":",
"[",
"0",
",",
"chartWidth",
"]",
";",
"xScale",
"=",
"d3Scale",
".",
"scaleLinear",
"(",
")",
".",
"domain",
"(",
"[",
"0",
",",
"Math",
".",
"max",
"(",
"ranges",
"[",
"0",
"]",
",",
"markers",
"[",
"0",
"]",
",",
"measures",
"[",
"0",
"]",
")",
"]",
")",
".",
"rangeRound",
"(",
"decidedRange",
")",
".",
"nice",
"(",
")",
";",
"// Derive width scales from x scales",
"barWidth",
"=",
"bulletWidth",
"(",
"xScale",
")",
";",
"// set up opacity scale based on ranges and measures",
"rangeOpacityScale",
"=",
"ranges",
".",
"map",
"(",
"(",
"d",
",",
"i",
")",
"=>",
"startMaxRangeOpacity",
"-",
"(",
"i",
"*",
"rangeOpacifyDiff",
")",
")",
".",
"reverse",
"(",
")",
";",
"measureOpacityScale",
"=",
"ranges",
".",
"map",
"(",
"(",
"d",
",",
"i",
")",
"=>",
"0.9",
"-",
"(",
"i",
"*",
"measureOpacifyDiff",
")",
")",
".",
"reverse",
"(",
")",
";",
"// initialize range and measure bars and marker line colors",
"rangeColor",
"=",
"colorSchema",
"[",
"0",
"]",
";",
"measureColor",
"=",
"colorSchema",
"[",
"1",
"]",
";",
"}"
] | Creates the x scales of the chart
@return {void}
@private | [
"Creates",
"the",
"x",
"scales",
"of",
"the",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L186-L204 |
8,530 | eventbrite/britecharts | src/charts/bullet.js | buildSVG | function buildSVG(container) {
if (!svg) {
svg = d3Selection.select(container)
.append('svg')
.classed('britechart bullet-chart', true);
buildContainerGroups();
}
svg
.attr('width', width)
.attr('height', height);
} | javascript | function buildSVG(container) {
if (!svg) {
svg = d3Selection.select(container)
.append('svg')
.classed('britechart bullet-chart', true);
buildContainerGroups();
}
svg
.attr('width', width)
.attr('height', height);
} | [
"function",
"buildSVG",
"(",
"container",
")",
"{",
"if",
"(",
"!",
"svg",
")",
"{",
"svg",
"=",
"d3Selection",
".",
"select",
"(",
"container",
")",
".",
"append",
"(",
"'svg'",
")",
".",
"classed",
"(",
"'britechart bullet-chart'",
",",
"true",
")",
";",
"buildContainerGroups",
"(",
")",
";",
"}",
"svg",
".",
"attr",
"(",
"'width'",
",",
"width",
")",
".",
"attr",
"(",
"'height'",
",",
"height",
")",
";",
"}"
] | Builds the SVG element that will contain the chart
@param {HTMLElement} container DOM element that will work as the container of the graph
@return {void}
@private | [
"Builds",
"the",
"SVG",
"element",
"that",
"will",
"contain",
"the",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L212-L224 |
8,531 | eventbrite/britecharts | src/charts/bullet.js | bulletWidth | function bulletWidth(x) {
const x0 = x(0);
return function (d) {
return Math.abs(x(d) - x0);
}
} | javascript | function bulletWidth(x) {
const x0 = x(0);
return function (d) {
return Math.abs(x(d) - x0);
}
} | [
"function",
"bulletWidth",
"(",
"x",
")",
"{",
"const",
"x0",
"=",
"x",
"(",
"0",
")",
";",
"return",
"function",
"(",
"d",
")",
"{",
"return",
"Math",
".",
"abs",
"(",
"x",
"(",
"d",
")",
"-",
"x0",
")",
";",
"}",
"}"
] | Calculates width for each bullet using scale
@return {void}
@private | [
"Calculates",
"width",
"for",
"each",
"bullet",
"using",
"scale"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L231-L237 |
8,532 | eventbrite/britecharts | src/charts/bullet.js | drawBullet | function drawBullet() {
if (rangesEl) {
rangesEl.remove();
measuresEl.remove();
markersEl.remove();
}
rangesEl = svg.select('.chart-group')
.selectAll('rect.range')
.data(ranges)
.enter()
.append('rect')
.attr('fill', rangeColor)
.attr('opacity', (d, i) => rangeOpacityScale[i])
.attr('class', (d, i) => `range r${i}`)
.attr('width', barWidth)
.attr('height', chartHeight)
.attr('x', isReverse ? xScale : 0);
measuresEl = svg.select('.chart-group')
.selectAll('rect.measure')
.data(measures)
.enter()
.append('rect')
.attr('fill', measureColor)
.attr('fill-opacity', (d, i) => measureOpacityScale[i])
.attr('class', (d, i) => `measure m${i}`)
.attr('width', barWidth)
.attr('height', getMeasureBarHeight)
.attr('x', isReverse ? xScale : 0)
.attr('y', getMeasureBarHeight);
markersEl = svg.select('.chart-group')
.selectAll('line.marker-line')
.data(markers)
.enter()
.append('line')
.attr('class', 'marker-line')
.attr('stroke', measureColor)
.attr('stroke-width', markerStrokeWidth)
.attr('opacity', measureOpacityScale[0])
.attr('x1', xScale)
.attr('x2', xScale)
.attr('y1', 0)
.attr('y2', chartHeight);
} | javascript | function drawBullet() {
if (rangesEl) {
rangesEl.remove();
measuresEl.remove();
markersEl.remove();
}
rangesEl = svg.select('.chart-group')
.selectAll('rect.range')
.data(ranges)
.enter()
.append('rect')
.attr('fill', rangeColor)
.attr('opacity', (d, i) => rangeOpacityScale[i])
.attr('class', (d, i) => `range r${i}`)
.attr('width', barWidth)
.attr('height', chartHeight)
.attr('x', isReverse ? xScale : 0);
measuresEl = svg.select('.chart-group')
.selectAll('rect.measure')
.data(measures)
.enter()
.append('rect')
.attr('fill', measureColor)
.attr('fill-opacity', (d, i) => measureOpacityScale[i])
.attr('class', (d, i) => `measure m${i}`)
.attr('width', barWidth)
.attr('height', getMeasureBarHeight)
.attr('x', isReverse ? xScale : 0)
.attr('y', getMeasureBarHeight);
markersEl = svg.select('.chart-group')
.selectAll('line.marker-line')
.data(markers)
.enter()
.append('line')
.attr('class', 'marker-line')
.attr('stroke', measureColor)
.attr('stroke-width', markerStrokeWidth)
.attr('opacity', measureOpacityScale[0])
.attr('x1', xScale)
.attr('x2', xScale)
.attr('y1', 0)
.attr('y2', chartHeight);
} | [
"function",
"drawBullet",
"(",
")",
"{",
"if",
"(",
"rangesEl",
")",
"{",
"rangesEl",
".",
"remove",
"(",
")",
";",
"measuresEl",
".",
"remove",
"(",
")",
";",
"markersEl",
".",
"remove",
"(",
")",
";",
"}",
"rangesEl",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'rect.range'",
")",
".",
"data",
"(",
"ranges",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'rect'",
")",
".",
"attr",
"(",
"'fill'",
",",
"rangeColor",
")",
".",
"attr",
"(",
"'opacity'",
",",
"(",
"d",
",",
"i",
")",
"=>",
"rangeOpacityScale",
"[",
"i",
"]",
")",
".",
"attr",
"(",
"'class'",
",",
"(",
"d",
",",
"i",
")",
"=>",
"`",
"${",
"i",
"}",
"`",
")",
".",
"attr",
"(",
"'width'",
",",
"barWidth",
")",
".",
"attr",
"(",
"'height'",
",",
"chartHeight",
")",
".",
"attr",
"(",
"'x'",
",",
"isReverse",
"?",
"xScale",
":",
"0",
")",
";",
"measuresEl",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'rect.measure'",
")",
".",
"data",
"(",
"measures",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'rect'",
")",
".",
"attr",
"(",
"'fill'",
",",
"measureColor",
")",
".",
"attr",
"(",
"'fill-opacity'",
",",
"(",
"d",
",",
"i",
")",
"=>",
"measureOpacityScale",
"[",
"i",
"]",
")",
".",
"attr",
"(",
"'class'",
",",
"(",
"d",
",",
"i",
")",
"=>",
"`",
"${",
"i",
"}",
"`",
")",
".",
"attr",
"(",
"'width'",
",",
"barWidth",
")",
".",
"attr",
"(",
"'height'",
",",
"getMeasureBarHeight",
")",
".",
"attr",
"(",
"'x'",
",",
"isReverse",
"?",
"xScale",
":",
"0",
")",
".",
"attr",
"(",
"'y'",
",",
"getMeasureBarHeight",
")",
";",
"markersEl",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'line.marker-line'",
")",
".",
"data",
"(",
"markers",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'line'",
")",
".",
"attr",
"(",
"'class'",
",",
"'marker-line'",
")",
".",
"attr",
"(",
"'stroke'",
",",
"measureColor",
")",
".",
"attr",
"(",
"'stroke-width'",
",",
"markerStrokeWidth",
")",
".",
"attr",
"(",
"'opacity'",
",",
"measureOpacityScale",
"[",
"0",
"]",
")",
".",
"attr",
"(",
"'x1'",
",",
"xScale",
")",
".",
"attr",
"(",
"'x2'",
",",
"xScale",
")",
".",
"attr",
"(",
"'y1'",
",",
"0",
")",
".",
"attr",
"(",
"'y2'",
",",
"chartHeight",
")",
";",
"}"
] | Draws the measures of the bullet chart
@return {void}
@private | [
"Draws",
"the",
"measures",
"of",
"the",
"bullet",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L282-L327 |
8,533 | eventbrite/britecharts | src/charts/bullet.js | drawTitles | function drawTitles() {
if (hasTitle()) {
// either use title provided from the data
// or customTitle provided via API method call
if (legendGroup) {
legendGroup.remove();
}
legendGroup = svg.select('.metadata-group')
.append('g')
.classed('legend-group', true)
.attr('transform', `translate(0, ${chartHeight / 2})`);
// override title with customTitle if given
if (customTitle) {
title = customTitle;
}
titleEl = legendGroup.selectAll('text.bullet-title')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-title x-axis-label')
.text(title);
// either use subtitle provided from the data
// or customSubtitle provided via API method call
if (subtitle || customSubtitle) {
// override subtitle with customSubtitle if given
if (customSubtitle) {
subtitle = customSubtitle;
}
titleEl = legendGroup.selectAll('text.bullet-subtitle')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-subtitle x-axis-label')
.attr('y', subtitleSpacing)
.text(subtitle);
}
}
} | javascript | function drawTitles() {
if (hasTitle()) {
// either use title provided from the data
// or customTitle provided via API method call
if (legendGroup) {
legendGroup.remove();
}
legendGroup = svg.select('.metadata-group')
.append('g')
.classed('legend-group', true)
.attr('transform', `translate(0, ${chartHeight / 2})`);
// override title with customTitle if given
if (customTitle) {
title = customTitle;
}
titleEl = legendGroup.selectAll('text.bullet-title')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-title x-axis-label')
.text(title);
// either use subtitle provided from the data
// or customSubtitle provided via API method call
if (subtitle || customSubtitle) {
// override subtitle with customSubtitle if given
if (customSubtitle) {
subtitle = customSubtitle;
}
titleEl = legendGroup.selectAll('text.bullet-subtitle')
.data([1])
.enter()
.append('text')
.attr('class', 'bullet-subtitle x-axis-label')
.attr('y', subtitleSpacing)
.text(subtitle);
}
}
} | [
"function",
"drawTitles",
"(",
")",
"{",
"if",
"(",
"hasTitle",
"(",
")",
")",
"{",
"// either use title provided from the data",
"// or customTitle provided via API method call",
"if",
"(",
"legendGroup",
")",
"{",
"legendGroup",
".",
"remove",
"(",
")",
";",
"}",
"legendGroup",
"=",
"svg",
".",
"select",
"(",
"'.metadata-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'legend-group'",
",",
"true",
")",
".",
"attr",
"(",
"'transform'",
",",
"`",
"${",
"chartHeight",
"/",
"2",
"}",
"`",
")",
";",
"// override title with customTitle if given",
"if",
"(",
"customTitle",
")",
"{",
"title",
"=",
"customTitle",
";",
"}",
"titleEl",
"=",
"legendGroup",
".",
"selectAll",
"(",
"'text.bullet-title'",
")",
".",
"data",
"(",
"[",
"1",
"]",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'text'",
")",
".",
"attr",
"(",
"'class'",
",",
"'bullet-title x-axis-label'",
")",
".",
"text",
"(",
"title",
")",
";",
"// either use subtitle provided from the data",
"// or customSubtitle provided via API method call",
"if",
"(",
"subtitle",
"||",
"customSubtitle",
")",
"{",
"// override subtitle with customSubtitle if given",
"if",
"(",
"customSubtitle",
")",
"{",
"subtitle",
"=",
"customSubtitle",
";",
"}",
"titleEl",
"=",
"legendGroup",
".",
"selectAll",
"(",
"'text.bullet-subtitle'",
")",
".",
"data",
"(",
"[",
"1",
"]",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'text'",
")",
".",
"attr",
"(",
"'class'",
",",
"'bullet-subtitle x-axis-label'",
")",
".",
"attr",
"(",
"'y'",
",",
"subtitleSpacing",
")",
".",
"text",
"(",
"subtitle",
")",
";",
"}",
"}",
"}"
] | Draws the title and subtitle components of chart
@return {void}
@private | [
"Draws",
"the",
"title",
"and",
"subtitle",
"components",
"of",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bullet.js#L350-L394 |
8,534 | eventbrite/britecharts | src/charts/bar.js | sortData | function sortData(unorderedData) {
let {data, dataZeroed} = unorderedData;
if (orderingFunction) {
data.sort(orderingFunction);
dataZeroed.sort(orderingFunction)
}
return { data, dataZeroed };
} | javascript | function sortData(unorderedData) {
let {data, dataZeroed} = unorderedData;
if (orderingFunction) {
data.sort(orderingFunction);
dataZeroed.sort(orderingFunction)
}
return { data, dataZeroed };
} | [
"function",
"sortData",
"(",
"unorderedData",
")",
"{",
"let",
"{",
"data",
",",
"dataZeroed",
"}",
"=",
"unorderedData",
";",
"if",
"(",
"orderingFunction",
")",
"{",
"data",
".",
"sort",
"(",
"orderingFunction",
")",
";",
"dataZeroed",
".",
"sort",
"(",
"orderingFunction",
")",
"}",
"return",
"{",
"data",
",",
"dataZeroed",
"}",
";",
"}"
] | Sorts data if orderingFunction is specified
@param {BarChartData} clean unordered data
@return {BarChartData} clean ordered data
@private | [
"Sorts",
"data",
"if",
"orderingFunction",
"is",
"specified"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L370-L379 |
8,535 | eventbrite/britecharts | src/charts/bar.js | drawAxisLabels | function drawAxisLabels() {
if (yAxisLabel) {
if (yAxisLabelEl) {
yAxisLabelEl.remove();
}
yAxisLabelEl = svg.select('.y-axis-label')
.append('text')
.classed('y-axis-label-text', true)
.attr('x', -chartHeight / 2)
.attr('y', yAxisLabelOffset)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270 0 0)')
.text(yAxisLabel);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
xAxisLabelEl.remove();
}
xAxisLabelEl = svg.select('.x-axis-label')
.append('text')
.attr('y', xAxisLabelOffset)
.attr('text-anchor', 'middle')
.classed('x-axis-label-text', true)
.attr('x', chartWidth / 2)
.text(xAxisLabel);
}
} | javascript | function drawAxisLabels() {
if (yAxisLabel) {
if (yAxisLabelEl) {
yAxisLabelEl.remove();
}
yAxisLabelEl = svg.select('.y-axis-label')
.append('text')
.classed('y-axis-label-text', true)
.attr('x', -chartHeight / 2)
.attr('y', yAxisLabelOffset)
.attr('text-anchor', 'middle')
.attr('transform', 'rotate(270 0 0)')
.text(yAxisLabel);
}
if (xAxisLabel) {
if (xAxisLabelEl) {
xAxisLabelEl.remove();
}
xAxisLabelEl = svg.select('.x-axis-label')
.append('text')
.attr('y', xAxisLabelOffset)
.attr('text-anchor', 'middle')
.classed('x-axis-label-text', true)
.attr('x', chartWidth / 2)
.text(xAxisLabel);
}
} | [
"function",
"drawAxisLabels",
"(",
")",
"{",
"if",
"(",
"yAxisLabel",
")",
"{",
"if",
"(",
"yAxisLabelEl",
")",
"{",
"yAxisLabelEl",
".",
"remove",
"(",
")",
";",
"}",
"yAxisLabelEl",
"=",
"svg",
".",
"select",
"(",
"'.y-axis-label'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"classed",
"(",
"'y-axis-label-text'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"-",
"chartHeight",
"/",
"2",
")",
".",
"attr",
"(",
"'y'",
",",
"yAxisLabelOffset",
")",
".",
"attr",
"(",
"'text-anchor'",
",",
"'middle'",
")",
".",
"attr",
"(",
"'transform'",
",",
"'rotate(270 0 0)'",
")",
".",
"text",
"(",
"yAxisLabel",
")",
";",
"}",
"if",
"(",
"xAxisLabel",
")",
"{",
"if",
"(",
"xAxisLabelEl",
")",
"{",
"xAxisLabelEl",
".",
"remove",
"(",
")",
";",
"}",
"xAxisLabelEl",
"=",
"svg",
".",
"select",
"(",
"'.x-axis-label'",
")",
".",
"append",
"(",
"'text'",
")",
".",
"attr",
"(",
"'y'",
",",
"xAxisLabelOffset",
")",
".",
"attr",
"(",
"'text-anchor'",
",",
"'middle'",
")",
".",
"classed",
"(",
"'x-axis-label-text'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"chartWidth",
"/",
"2",
")",
".",
"text",
"(",
"xAxisLabel",
")",
";",
"}",
"}"
] | Draws the x and y axis custom labels respective groups
@private | [
"Draws",
"the",
"x",
"and",
"y",
"axis",
"custom",
"labels",
"respective",
"groups"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L414-L441 |
8,536 | eventbrite/britecharts | src/charts/bar.js | drawAnimatedHorizontalBars | function drawAnimatedHorizontalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', 0)
.attr('y', chartHeight)
.attr('height', yScale.bandwidth())
.attr('width', ({value}) => xScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
});
bars
.attr('x', 0)
.attr('y', ({name}) => yScale(name))
.attr('height', yScale.bandwidth())
.attr('fill', ({name}) => computeColor(name))
.transition()
.duration(animationDuration)
.delay(interBarDelay)
.ease(ease)
.attr('width', ({value}) => xScale(value));
} | javascript | function drawAnimatedHorizontalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', 0)
.attr('y', chartHeight)
.attr('height', yScale.bandwidth())
.attr('width', ({value}) => xScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
});
bars
.attr('x', 0)
.attr('y', ({name}) => yScale(name))
.attr('height', yScale.bandwidth())
.attr('fill', ({name}) => computeColor(name))
.transition()
.duration(animationDuration)
.delay(interBarDelay)
.ease(ease)
.attr('width', ({value}) => xScale(value));
} | [
"function",
"drawAnimatedHorizontalBars",
"(",
"bars",
")",
"{",
"// Enter + Update",
"bars",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'rect'",
")",
".",
"classed",
"(",
"'bar'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"0",
")",
".",
"attr",
"(",
"'y'",
",",
"chartHeight",
")",
".",
"attr",
"(",
"'height'",
",",
"yScale",
".",
"bandwidth",
"(",
")",
")",
".",
"attr",
"(",
"'width'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"xScale",
"(",
"value",
")",
")",
".",
"on",
"(",
"'mouseover'",
",",
"function",
"(",
"d",
",",
"index",
",",
"barList",
")",
"{",
"handleMouseOver",
"(",
"this",
",",
"d",
",",
"barList",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'mousemove'",
",",
"function",
"(",
"d",
")",
"{",
"handleMouseMove",
"(",
"this",
",",
"d",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'mouseout'",
",",
"function",
"(",
"d",
",",
"index",
",",
"barList",
")",
"{",
"handleMouseOut",
"(",
"this",
",",
"d",
",",
"barList",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
"d",
")",
"{",
"handleClick",
"(",
"this",
",",
"d",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
";",
"bars",
".",
"attr",
"(",
"'x'",
",",
"0",
")",
".",
"attr",
"(",
"'y'",
",",
"(",
"{",
"name",
"}",
")",
"=>",
"yScale",
"(",
"name",
")",
")",
".",
"attr",
"(",
"'height'",
",",
"yScale",
".",
"bandwidth",
"(",
")",
")",
".",
"attr",
"(",
"'fill'",
",",
"(",
"{",
"name",
"}",
")",
"=>",
"computeColor",
"(",
"name",
")",
")",
".",
"transition",
"(",
")",
".",
"duration",
"(",
"animationDuration",
")",
".",
"delay",
"(",
"interBarDelay",
")",
".",
"ease",
"(",
"ease",
")",
".",
"attr",
"(",
"'width'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"xScale",
"(",
"value",
")",
")",
";",
"}"
] | Draws and animates the bars along the x axis
@param {D3Selection} bars Selection of bars
@return {void} | [
"Draws",
"and",
"animates",
"the",
"bars",
"along",
"the",
"x",
"axis"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L482-L514 |
8,537 | eventbrite/britecharts | src/charts/bar.js | drawVerticalBars | function drawVerticalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', chartWidth)
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
})
.merge(bars)
.attr('x', ({name}) => xScale(name))
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.attr('fill', ({name}) => computeColor(name));
} | javascript | function drawVerticalBars(bars) {
// Enter + Update
bars.enter()
.append('rect')
.classed('bar', true)
.attr('x', chartWidth)
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.on('mouseover', function(d, index, barList) {
handleMouseOver(this, d, barList, chartWidth, chartHeight);
})
.on('mousemove', function(d) {
handleMouseMove(this, d, chartWidth, chartHeight);
})
.on('mouseout', function(d, index, barList) {
handleMouseOut(this, d, barList, chartWidth, chartHeight);
})
.on('click', function(d) {
handleClick(this, d, chartWidth, chartHeight);
})
.merge(bars)
.attr('x', ({name}) => xScale(name))
.attr('y', ({value}) => yScale(value))
.attr('width', xScale.bandwidth())
.attr('height', ({value}) => chartHeight - yScale(value))
.attr('fill', ({name}) => computeColor(name));
} | [
"function",
"drawVerticalBars",
"(",
"bars",
")",
"{",
"// Enter + Update",
"bars",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'rect'",
")",
".",
"classed",
"(",
"'bar'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"chartWidth",
")",
".",
"attr",
"(",
"'y'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"yScale",
"(",
"value",
")",
")",
".",
"attr",
"(",
"'width'",
",",
"xScale",
".",
"bandwidth",
"(",
")",
")",
".",
"attr",
"(",
"'height'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"chartHeight",
"-",
"yScale",
"(",
"value",
")",
")",
".",
"on",
"(",
"'mouseover'",
",",
"function",
"(",
"d",
",",
"index",
",",
"barList",
")",
"{",
"handleMouseOver",
"(",
"this",
",",
"d",
",",
"barList",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'mousemove'",
",",
"function",
"(",
"d",
")",
"{",
"handleMouseMove",
"(",
"this",
",",
"d",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'mouseout'",
",",
"function",
"(",
"d",
",",
"index",
",",
"barList",
")",
"{",
"handleMouseOut",
"(",
"this",
",",
"d",
",",
"barList",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
"d",
")",
"{",
"handleClick",
"(",
"this",
",",
"d",
",",
"chartWidth",
",",
"chartHeight",
")",
";",
"}",
")",
".",
"merge",
"(",
"bars",
")",
".",
"attr",
"(",
"'x'",
",",
"(",
"{",
"name",
"}",
")",
"=>",
"xScale",
"(",
"name",
")",
")",
".",
"attr",
"(",
"'y'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"yScale",
"(",
"value",
")",
")",
".",
"attr",
"(",
"'width'",
",",
"xScale",
".",
"bandwidth",
"(",
")",
")",
".",
"attr",
"(",
"'height'",
",",
"(",
"{",
"value",
"}",
")",
"=>",
"chartHeight",
"-",
"yScale",
"(",
"value",
")",
")",
".",
"attr",
"(",
"'fill'",
",",
"(",
"{",
"name",
"}",
")",
"=>",
"computeColor",
"(",
"name",
")",
")",
";",
"}"
] | Draws the bars along the y axis
@param {D3Selection} bars Selection of bars
@return {void} | [
"Draws",
"the",
"bars",
"along",
"the",
"y",
"axis"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L559-L586 |
8,538 | eventbrite/britecharts | src/charts/bar.js | drawLabels | function drawLabels() {
let labelXPosition = isHorizontal ? _labelsHorizontalX : _labelsVerticalX;
let labelYPosition = isHorizontal ? _labelsHorizontalY : _labelsVerticalY;
let text = _labelsFormatValue
if (labelEl) {
svg.selectAll('.percentage-label-group').remove();
}
labelEl = svg.select('.metadata-group')
.append('g')
.classed('percentage-label-group', true)
.selectAll('text')
.data(data.reverse())
.enter()
.append('text');
labelEl
.classed('percentage-label', true)
.attr('x', labelXPosition)
.attr('y', labelYPosition)
.text(text)
.attr('font-size', labelsSize + 'px')
} | javascript | function drawLabels() {
let labelXPosition = isHorizontal ? _labelsHorizontalX : _labelsVerticalX;
let labelYPosition = isHorizontal ? _labelsHorizontalY : _labelsVerticalY;
let text = _labelsFormatValue
if (labelEl) {
svg.selectAll('.percentage-label-group').remove();
}
labelEl = svg.select('.metadata-group')
.append('g')
.classed('percentage-label-group', true)
.selectAll('text')
.data(data.reverse())
.enter()
.append('text');
labelEl
.classed('percentage-label', true)
.attr('x', labelXPosition)
.attr('y', labelYPosition)
.text(text)
.attr('font-size', labelsSize + 'px')
} | [
"function",
"drawLabels",
"(",
")",
"{",
"let",
"labelXPosition",
"=",
"isHorizontal",
"?",
"_labelsHorizontalX",
":",
"_labelsVerticalX",
";",
"let",
"labelYPosition",
"=",
"isHorizontal",
"?",
"_labelsHorizontalY",
":",
"_labelsVerticalY",
";",
"let",
"text",
"=",
"_labelsFormatValue",
"if",
"(",
"labelEl",
")",
"{",
"svg",
".",
"selectAll",
"(",
"'.percentage-label-group'",
")",
".",
"remove",
"(",
")",
";",
"}",
"labelEl",
"=",
"svg",
".",
"select",
"(",
"'.metadata-group'",
")",
".",
"append",
"(",
"'g'",
")",
".",
"classed",
"(",
"'percentage-label-group'",
",",
"true",
")",
".",
"selectAll",
"(",
"'text'",
")",
".",
"data",
"(",
"data",
".",
"reverse",
"(",
")",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'text'",
")",
";",
"labelEl",
".",
"classed",
"(",
"'percentage-label'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"labelXPosition",
")",
".",
"attr",
"(",
"'y'",
",",
"labelYPosition",
")",
".",
"text",
"(",
"text",
")",
".",
"attr",
"(",
"'font-size'",
",",
"labelsSize",
"+",
"'px'",
")",
"}"
] | Draws labels at the end of each bar
@private
@return {void} | [
"Draws",
"labels",
"at",
"the",
"end",
"of",
"each",
"bar"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L593-L616 |
8,539 | eventbrite/britecharts | src/charts/bar.js | drawBars | function drawBars() {
let bars;
if (isAnimated) {
bars = svg.select('.chart-group').selectAll('.bar')
.data(dataZeroed);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawAnimatedHorizontalBars(bars);
} else {
drawAnimatedVerticalBars(bars);
}
// Exit
bars.exit()
.transition()
.style('opacity', 0)
.remove();
} else {
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
// Exit
bars.exit()
.remove();
}
} | javascript | function drawBars() {
let bars;
if (isAnimated) {
bars = svg.select('.chart-group').selectAll('.bar')
.data(dataZeroed);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawAnimatedHorizontalBars(bars);
} else {
drawAnimatedVerticalBars(bars);
}
// Exit
bars.exit()
.transition()
.style('opacity', 0)
.remove();
} else {
bars = svg.select('.chart-group').selectAll('.bar')
.data(data);
if (isHorizontal) {
drawHorizontalBars(bars);
} else {
drawVerticalBars(bars);
}
// Exit
bars.exit()
.remove();
}
} | [
"function",
"drawBars",
"(",
")",
"{",
"let",
"bars",
";",
"if",
"(",
"isAnimated",
")",
"{",
"bars",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'.bar'",
")",
".",
"data",
"(",
"dataZeroed",
")",
";",
"if",
"(",
"isHorizontal",
")",
"{",
"drawHorizontalBars",
"(",
"bars",
")",
";",
"}",
"else",
"{",
"drawVerticalBars",
"(",
"bars",
")",
";",
"}",
"bars",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'.bar'",
")",
".",
"data",
"(",
"data",
")",
";",
"if",
"(",
"isHorizontal",
")",
"{",
"drawAnimatedHorizontalBars",
"(",
"bars",
")",
";",
"}",
"else",
"{",
"drawAnimatedVerticalBars",
"(",
"bars",
")",
";",
"}",
"// Exit",
"bars",
".",
"exit",
"(",
")",
".",
"transition",
"(",
")",
".",
"style",
"(",
"'opacity'",
",",
"0",
")",
".",
"remove",
"(",
")",
";",
"}",
"else",
"{",
"bars",
"=",
"svg",
".",
"select",
"(",
"'.chart-group'",
")",
".",
"selectAll",
"(",
"'.bar'",
")",
".",
"data",
"(",
"data",
")",
";",
"if",
"(",
"isHorizontal",
")",
"{",
"drawHorizontalBars",
"(",
"bars",
")",
";",
"}",
"else",
"{",
"drawVerticalBars",
"(",
"bars",
")",
";",
"}",
"// Exit",
"bars",
".",
"exit",
"(",
")",
".",
"remove",
"(",
")",
";",
"}",
"}"
] | Draws the bar elements within the chart group
@private | [
"Draws",
"the",
"bar",
"elements",
"within",
"the",
"chart",
"group"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L622-L664 |
8,540 | eventbrite/britecharts | src/charts/bar.js | drawHorizontalGridLines | function drawHorizontalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.vertical-grid-line')
.data(xScale.ticks(xTicks).slice(1))
.enter()
.append('line')
.attr('class', 'vertical-grid-line')
.attr('y1', (xAxisPadding.left))
.attr('y2', chartHeight)
.attr('x1', (d) => xScale(d))
.attr('x2', (d) => xScale(d))
drawVerticalExtendedLine();
} | javascript | function drawHorizontalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.vertical-grid-line')
.data(xScale.ticks(xTicks).slice(1))
.enter()
.append('line')
.attr('class', 'vertical-grid-line')
.attr('y1', (xAxisPadding.left))
.attr('y2', chartHeight)
.attr('x1', (d) => xScale(d))
.attr('x2', (d) => xScale(d))
drawVerticalExtendedLine();
} | [
"function",
"drawHorizontalGridLines",
"(",
")",
"{",
"maskGridLines",
"=",
"svg",
".",
"select",
"(",
"'.grid-lines-group'",
")",
".",
"selectAll",
"(",
"'line.vertical-grid-line'",
")",
".",
"data",
"(",
"xScale",
".",
"ticks",
"(",
"xTicks",
")",
".",
"slice",
"(",
"1",
")",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'line'",
")",
".",
"attr",
"(",
"'class'",
",",
"'vertical-grid-line'",
")",
".",
"attr",
"(",
"'y1'",
",",
"(",
"xAxisPadding",
".",
"left",
")",
")",
".",
"attr",
"(",
"'y2'",
",",
"chartHeight",
")",
".",
"attr",
"(",
"'x1'",
",",
"(",
"d",
")",
"=>",
"xScale",
"(",
"d",
")",
")",
".",
"attr",
"(",
"'x2'",
",",
"(",
"d",
")",
"=>",
"xScale",
"(",
"d",
")",
")",
"drawVerticalExtendedLine",
"(",
")",
";",
"}"
] | Draws the grid lines for an horizontal bar chart
@return {void} | [
"Draws",
"the",
"grid",
"lines",
"for",
"an",
"horizontal",
"bar",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L686-L699 |
8,541 | eventbrite/britecharts | src/charts/bar.js | drawVerticalExtendedLine | function drawVerticalExtendedLine() {
baseLine = svg.select('.grid-lines-group')
.selectAll('line.extended-y-line')
.data([0])
.enter()
.append('line')
.attr('class', 'extended-y-line')
.attr('y1', (xAxisPadding.bottom))
.attr('y2', chartHeight)
.attr('x1', 0)
.attr('x2', 0);
} | javascript | function drawVerticalExtendedLine() {
baseLine = svg.select('.grid-lines-group')
.selectAll('line.extended-y-line')
.data([0])
.enter()
.append('line')
.attr('class', 'extended-y-line')
.attr('y1', (xAxisPadding.bottom))
.attr('y2', chartHeight)
.attr('x1', 0)
.attr('x2', 0);
} | [
"function",
"drawVerticalExtendedLine",
"(",
")",
"{",
"baseLine",
"=",
"svg",
".",
"select",
"(",
"'.grid-lines-group'",
")",
".",
"selectAll",
"(",
"'line.extended-y-line'",
")",
".",
"data",
"(",
"[",
"0",
"]",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'line'",
")",
".",
"attr",
"(",
"'class'",
",",
"'extended-y-line'",
")",
".",
"attr",
"(",
"'y1'",
",",
"(",
"xAxisPadding",
".",
"bottom",
")",
")",
".",
"attr",
"(",
"'y2'",
",",
"chartHeight",
")",
".",
"attr",
"(",
"'x1'",
",",
"0",
")",
".",
"attr",
"(",
"'x2'",
",",
"0",
")",
";",
"}"
] | Draws a vertical line to extend y-axis till the edges
@return {void} | [
"Draws",
"a",
"vertical",
"line",
"to",
"extend",
"y",
"-",
"axis",
"till",
"the",
"edges"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L705-L716 |
8,542 | eventbrite/britecharts | src/charts/bar.js | drawVerticalGridLines | function drawVerticalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.horizontal-grid-line')
.data(yScale.ticks(yTicks).slice(1))
.enter()
.append('line')
.attr('class', 'horizontal-grid-line')
.attr('x1', (xAxisPadding.left))
.attr('x2', chartWidth)
.attr('y1', (d) => yScale(d))
.attr('y2', (d) => yScale(d))
drawHorizontalExtendedLine();
} | javascript | function drawVerticalGridLines() {
maskGridLines = svg.select('.grid-lines-group')
.selectAll('line.horizontal-grid-line')
.data(yScale.ticks(yTicks).slice(1))
.enter()
.append('line')
.attr('class', 'horizontal-grid-line')
.attr('x1', (xAxisPadding.left))
.attr('x2', chartWidth)
.attr('y1', (d) => yScale(d))
.attr('y2', (d) => yScale(d))
drawHorizontalExtendedLine();
} | [
"function",
"drawVerticalGridLines",
"(",
")",
"{",
"maskGridLines",
"=",
"svg",
".",
"select",
"(",
"'.grid-lines-group'",
")",
".",
"selectAll",
"(",
"'line.horizontal-grid-line'",
")",
".",
"data",
"(",
"yScale",
".",
"ticks",
"(",
"yTicks",
")",
".",
"slice",
"(",
"1",
")",
")",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'line'",
")",
".",
"attr",
"(",
"'class'",
",",
"'horizontal-grid-line'",
")",
".",
"attr",
"(",
"'x1'",
",",
"(",
"xAxisPadding",
".",
"left",
")",
")",
".",
"attr",
"(",
"'x2'",
",",
"chartWidth",
")",
".",
"attr",
"(",
"'y1'",
",",
"(",
"d",
")",
"=>",
"yScale",
"(",
"d",
")",
")",
".",
"attr",
"(",
"'y2'",
",",
"(",
"d",
")",
"=>",
"yScale",
"(",
"d",
")",
")",
"drawHorizontalExtendedLine",
"(",
")",
";",
"}"
] | Draws the grid lines for a vertical bar chart
@return {void} | [
"Draws",
"the",
"grid",
"lines",
"for",
"a",
"vertical",
"bar",
"chart"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/bar.js#L722-L735 |
8,543 | eventbrite/britecharts | src/charts/grouped-bar.js | buildLayers | function buildLayers() {
layers = transformedData.map((item) => {
let ret = {};
groups.forEach((key) => {
ret[key] = item[key];
});
return assign({}, item, ret);
});
} | javascript | function buildLayers() {
layers = transformedData.map((item) => {
let ret = {};
groups.forEach((key) => {
ret[key] = item[key];
});
return assign({}, item, ret);
});
} | [
"function",
"buildLayers",
"(",
")",
"{",
"layers",
"=",
"transformedData",
".",
"map",
"(",
"(",
"item",
")",
"=>",
"{",
"let",
"ret",
"=",
"{",
"}",
";",
"groups",
".",
"forEach",
"(",
"(",
"key",
")",
"=>",
"{",
"ret",
"[",
"key",
"]",
"=",
"item",
"[",
"key",
"]",
";",
"}",
")",
";",
"return",
"assign",
"(",
"{",
"}",
",",
"item",
",",
"ret",
")",
";",
"}",
")",
";",
"}"
] | Builds the grouped layers layout
@return {D3Layout} Layout for drawing the chart
@private | [
"Builds",
"the",
"grouped",
"layers",
"layout"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L267-L277 |
8,544 | eventbrite/britecharts | src/charts/grouped-bar.js | cleanData | function cleanData(originalData) {
return originalData.reduce((acc, d) => {
d.value = +d[valueLabel];
d.group = d[groupLabel];
// for tooltip
d.topicName = getGroup(d);
d.name = d[nameLabel];
return [...acc, d];
}, []);
} | javascript | function cleanData(originalData) {
return originalData.reduce((acc, d) => {
d.value = +d[valueLabel];
d.group = d[groupLabel];
// for tooltip
d.topicName = getGroup(d);
d.name = d[nameLabel];
return [...acc, d];
}, []);
} | [
"function",
"cleanData",
"(",
"originalData",
")",
"{",
"return",
"originalData",
".",
"reduce",
"(",
"(",
"acc",
",",
"d",
")",
"=>",
"{",
"d",
".",
"value",
"=",
"+",
"d",
"[",
"valueLabel",
"]",
";",
"d",
".",
"group",
"=",
"d",
"[",
"groupLabel",
"]",
";",
"// for tooltip",
"d",
".",
"topicName",
"=",
"getGroup",
"(",
"d",
")",
";",
"d",
".",
"name",
"=",
"d",
"[",
"nameLabel",
"]",
";",
"return",
"[",
"...",
"acc",
",",
"d",
"]",
";",
"}",
",",
"[",
"]",
")",
";",
"}"
] | Cleaning data casting the values, groups, topic names and names to the proper type while keeping
the rest of properties on the data
@param {GroupedBarChartData} originalData Raw data from the container
@return {GroupedBarChartData} Parsed data with values and dates
@private | [
"Cleaning",
"data",
"casting",
"the",
"values",
"groups",
"topic",
"names",
"and",
"names",
"to",
"the",
"proper",
"type",
"while",
"keeping",
"the",
"rest",
"of",
"properties",
"on",
"the",
"data"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L360-L370 |
8,545 | eventbrite/britecharts | src/charts/grouped-bar.js | drawHorizontalBars | function drawHorizontalBars(layersSelection) {
let layerJoin = layersSelection
.data(layers);
layerElements = layerJoin
.enter()
.append('g')
.attr('transform', ({key}) => `translate(0,${yScale(key)})`)
.classed('layer', true);
let barJoin = layerElements
.selectAll('.bar')
.data(({values}) => values);
// Enter + Update
let bars = barJoin
.enter()
.append('rect')
.classed('bar', true)
.attr('x', 1)
.attr('y', (d) => yScale2(getGroup(d)))
.attr('height', yScale2.bandwidth())
.attr('fill', (({group}) => categoryColorMap[group]));
if (isAnimated) {
bars.style('opacity', barOpacity)
.transition()
.delay((_, i) => animationDelays[i])
.duration(animationDuration)
.ease(ease)
.tween('attr.width', horizontalBarsTween);
} else {
bars.attr('width', (d) => xScale(getValue(d)));
}
} | javascript | function drawHorizontalBars(layersSelection) {
let layerJoin = layersSelection
.data(layers);
layerElements = layerJoin
.enter()
.append('g')
.attr('transform', ({key}) => `translate(0,${yScale(key)})`)
.classed('layer', true);
let barJoin = layerElements
.selectAll('.bar')
.data(({values}) => values);
// Enter + Update
let bars = barJoin
.enter()
.append('rect')
.classed('bar', true)
.attr('x', 1)
.attr('y', (d) => yScale2(getGroup(d)))
.attr('height', yScale2.bandwidth())
.attr('fill', (({group}) => categoryColorMap[group]));
if (isAnimated) {
bars.style('opacity', barOpacity)
.transition()
.delay((_, i) => animationDelays[i])
.duration(animationDuration)
.ease(ease)
.tween('attr.width', horizontalBarsTween);
} else {
bars.attr('width', (d) => xScale(getValue(d)));
}
} | [
"function",
"drawHorizontalBars",
"(",
"layersSelection",
")",
"{",
"let",
"layerJoin",
"=",
"layersSelection",
".",
"data",
"(",
"layers",
")",
";",
"layerElements",
"=",
"layerJoin",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'g'",
")",
".",
"attr",
"(",
"'transform'",
",",
"(",
"{",
"key",
"}",
")",
"=>",
"`",
"${",
"yScale",
"(",
"key",
")",
"}",
"`",
")",
".",
"classed",
"(",
"'layer'",
",",
"true",
")",
";",
"let",
"barJoin",
"=",
"layerElements",
".",
"selectAll",
"(",
"'.bar'",
")",
".",
"data",
"(",
"(",
"{",
"values",
"}",
")",
"=>",
"values",
")",
";",
"// Enter + Update",
"let",
"bars",
"=",
"barJoin",
".",
"enter",
"(",
")",
".",
"append",
"(",
"'rect'",
")",
".",
"classed",
"(",
"'bar'",
",",
"true",
")",
".",
"attr",
"(",
"'x'",
",",
"1",
")",
".",
"attr",
"(",
"'y'",
",",
"(",
"d",
")",
"=>",
"yScale2",
"(",
"getGroup",
"(",
"d",
")",
")",
")",
".",
"attr",
"(",
"'height'",
",",
"yScale2",
".",
"bandwidth",
"(",
")",
")",
".",
"attr",
"(",
"'fill'",
",",
"(",
"(",
"{",
"group",
"}",
")",
"=>",
"categoryColorMap",
"[",
"group",
"]",
")",
")",
";",
"if",
"(",
"isAnimated",
")",
"{",
"bars",
".",
"style",
"(",
"'opacity'",
",",
"barOpacity",
")",
".",
"transition",
"(",
")",
".",
"delay",
"(",
"(",
"_",
",",
"i",
")",
"=>",
"animationDelays",
"[",
"i",
"]",
")",
".",
"duration",
"(",
"animationDuration",
")",
".",
"ease",
"(",
"ease",
")",
".",
"tween",
"(",
"'attr.width'",
",",
"horizontalBarsTween",
")",
";",
"}",
"else",
"{",
"bars",
".",
"attr",
"(",
"'width'",
",",
"(",
"d",
")",
"=>",
"xScale",
"(",
"getValue",
"(",
"d",
")",
")",
")",
";",
"}",
"}"
] | Draws the bars along the x axis
@param {D3Selection} layersSelection Selection of layers
@return {void} | [
"Draws",
"the",
"bars",
"along",
"the",
"x",
"axis"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L496-L530 |
8,546 | eventbrite/britecharts | src/charts/grouped-bar.js | handleBarsMouseOver | function handleBarsMouseOver(e, d) {
d3Selection.select(e)
.attr('fill', () => d3Color.color(categoryColorMap[d.group]).darker());
} | javascript | function handleBarsMouseOver(e, d) {
d3Selection.select(e)
.attr('fill', () => d3Color.color(categoryColorMap[d.group]).darker());
} | [
"function",
"handleBarsMouseOver",
"(",
"e",
",",
"d",
")",
"{",
"d3Selection",
".",
"select",
"(",
"e",
")",
".",
"attr",
"(",
"'fill'",
",",
"(",
")",
"=>",
"d3Color",
".",
"color",
"(",
"categoryColorMap",
"[",
"d",
".",
"group",
"]",
")",
".",
"darker",
"(",
")",
")",
";",
"}"
] | Handles a mouseover event on top of a bar
@param {obj} e the fired event
@param {obj} d data of bar
@return {void} | [
"Handles",
"a",
"mouseover",
"event",
"on",
"top",
"of",
"a",
"bar"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L661-L664 |
8,547 | eventbrite/britecharts | src/charts/grouped-bar.js | handleBarsMouseOut | function handleBarsMouseOut(e, d) {
d3Selection.select(e)
.attr('fill', () => categoryColorMap[d.group])
} | javascript | function handleBarsMouseOut(e, d) {
d3Selection.select(e)
.attr('fill', () => categoryColorMap[d.group])
} | [
"function",
"handleBarsMouseOut",
"(",
"e",
",",
"d",
")",
"{",
"d3Selection",
".",
"select",
"(",
"e",
")",
".",
"attr",
"(",
"'fill'",
",",
"(",
")",
"=>",
"categoryColorMap",
"[",
"d",
".",
"group",
"]",
")",
"}"
] | Handles a mouseout event out of a bar
@param {obj} e the fired event
@param {obj} d data of bar
@return {void} | [
"Handles",
"a",
"mouseout",
"event",
"out",
"of",
"a",
"bar"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L672-L675 |
8,548 | eventbrite/britecharts | src/charts/grouped-bar.js | handleCustomClick | function handleCustomClick (e, d) {
let [mouseX, mouseY] = getMousePosition(e);
let dataPoint = isHorizontal ? getNearestDataPoint2(mouseY) : getNearestDataPoint(mouseX);
dispatcher.call('customClick', e, dataPoint, d3Selection.mouse(e));
} | javascript | function handleCustomClick (e, d) {
let [mouseX, mouseY] = getMousePosition(e);
let dataPoint = isHorizontal ? getNearestDataPoint2(mouseY) : getNearestDataPoint(mouseX);
dispatcher.call('customClick', e, dataPoint, d3Selection.mouse(e));
} | [
"function",
"handleCustomClick",
"(",
"e",
",",
"d",
")",
"{",
"let",
"[",
"mouseX",
",",
"mouseY",
"]",
"=",
"getMousePosition",
"(",
"e",
")",
";",
"let",
"dataPoint",
"=",
"isHorizontal",
"?",
"getNearestDataPoint2",
"(",
"mouseY",
")",
":",
"getNearestDataPoint",
"(",
"mouseX",
")",
";",
"dispatcher",
".",
"call",
"(",
"'customClick'",
",",
"e",
",",
"dataPoint",
",",
"d3Selection",
".",
"mouse",
"(",
"e",
")",
")",
";",
"}"
] | Click handler, shows data that was clicked and passes to the user
@private | [
"Click",
"handler",
"shows",
"data",
"that",
"was",
"clicked",
"and",
"passes",
"to",
"the",
"user"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L709-L714 |
8,549 | eventbrite/britecharts | src/charts/grouped-bar.js | horizontalBarsTween | function horizontalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, xScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('width', i(t))
.style('opacity', j(t));
}
} | javascript | function horizontalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, xScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('width', i(t))
.style('opacity', j(t));
}
} | [
"function",
"horizontalBarsTween",
"(",
"d",
")",
"{",
"let",
"node",
"=",
"d3Selection",
".",
"select",
"(",
"this",
")",
",",
"i",
"=",
"d3Interpolate",
".",
"interpolateRound",
"(",
"0",
",",
"xScale",
"(",
"getValue",
"(",
"d",
")",
")",
")",
",",
"j",
"=",
"d3Interpolate",
".",
"interpolateNumber",
"(",
"0",
",",
"1",
")",
";",
"return",
"function",
"(",
"t",
")",
"{",
"node",
".",
"attr",
"(",
"'width'",
",",
"i",
"(",
"t",
")",
")",
".",
"style",
"(",
"'opacity'",
",",
"j",
"(",
"t",
")",
")",
";",
"}",
"}"
] | Animation tween of horizontal bars
@param {obj} d data of bar
@return {void} | [
"Animation",
"tween",
"of",
"horizontal",
"bars"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L739-L748 |
8,550 | eventbrite/britecharts | src/charts/grouped-bar.js | prepareData | function prepareData(data) {
groups = uniq(data.map((d) => getGroup(d)));
transformedData = d3Collection.nest()
.key(getName)
.rollup(function (values) {
let ret = {};
values.forEach((entry) => {
if (entry && entry[groupLabel]) {
ret[entry[groupLabel]] = getValue(entry);
}
});
//for tooltip
ret.values = values;
return ret;
})
.entries(data)
.map(function (data) {
return assign({}, {
total: d3Array.sum(d3Array.permute(data.value, groups)),
key: data.key
}, data.value);
});
} | javascript | function prepareData(data) {
groups = uniq(data.map((d) => getGroup(d)));
transformedData = d3Collection.nest()
.key(getName)
.rollup(function (values) {
let ret = {};
values.forEach((entry) => {
if (entry && entry[groupLabel]) {
ret[entry[groupLabel]] = getValue(entry);
}
});
//for tooltip
ret.values = values;
return ret;
})
.entries(data)
.map(function (data) {
return assign({}, {
total: d3Array.sum(d3Array.permute(data.value, groups)),
key: data.key
}, data.value);
});
} | [
"function",
"prepareData",
"(",
"data",
")",
"{",
"groups",
"=",
"uniq",
"(",
"data",
".",
"map",
"(",
"(",
"d",
")",
"=>",
"getGroup",
"(",
"d",
")",
")",
")",
";",
"transformedData",
"=",
"d3Collection",
".",
"nest",
"(",
")",
".",
"key",
"(",
"getName",
")",
".",
"rollup",
"(",
"function",
"(",
"values",
")",
"{",
"let",
"ret",
"=",
"{",
"}",
";",
"values",
".",
"forEach",
"(",
"(",
"entry",
")",
"=>",
"{",
"if",
"(",
"entry",
"&&",
"entry",
"[",
"groupLabel",
"]",
")",
"{",
"ret",
"[",
"entry",
"[",
"groupLabel",
"]",
"]",
"=",
"getValue",
"(",
"entry",
")",
";",
"}",
"}",
")",
";",
"//for tooltip",
"ret",
".",
"values",
"=",
"values",
";",
"return",
"ret",
";",
"}",
")",
".",
"entries",
"(",
"data",
")",
".",
"map",
"(",
"function",
"(",
"data",
")",
"{",
"return",
"assign",
"(",
"{",
"}",
",",
"{",
"total",
":",
"d3Array",
".",
"sum",
"(",
"d3Array",
".",
"permute",
"(",
"data",
".",
"value",
",",
"groups",
")",
")",
",",
"key",
":",
"data",
".",
"key",
"}",
",",
"data",
".",
"value",
")",
";",
"}",
")",
";",
"}"
] | Prepare data for create chart.
@private | [
"Prepare",
"data",
"for",
"create",
"chart",
"."
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L764-L787 |
8,551 | eventbrite/britecharts | src/charts/grouped-bar.js | verticalBarsTween | function verticalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, chartHeight - yScale(getValue(d))),
y = d3Interpolate.interpolateRound(chartHeight, yScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('y', y(t))
.attr('height', i(t)).style('opacity', j(t));
}
} | javascript | function verticalBarsTween(d) {
let node = d3Selection.select(this),
i = d3Interpolate.interpolateRound(0, chartHeight - yScale(getValue(d))),
y = d3Interpolate.interpolateRound(chartHeight, yScale(getValue(d))),
j = d3Interpolate.interpolateNumber(0, 1);
return function (t) {
node.attr('y', y(t))
.attr('height', i(t)).style('opacity', j(t));
}
} | [
"function",
"verticalBarsTween",
"(",
"d",
")",
"{",
"let",
"node",
"=",
"d3Selection",
".",
"select",
"(",
"this",
")",
",",
"i",
"=",
"d3Interpolate",
".",
"interpolateRound",
"(",
"0",
",",
"chartHeight",
"-",
"yScale",
"(",
"getValue",
"(",
"d",
")",
")",
")",
",",
"y",
"=",
"d3Interpolate",
".",
"interpolateRound",
"(",
"chartHeight",
",",
"yScale",
"(",
"getValue",
"(",
"d",
")",
")",
")",
",",
"j",
"=",
"d3Interpolate",
".",
"interpolateNumber",
"(",
"0",
",",
"1",
")",
";",
"return",
"function",
"(",
"t",
")",
"{",
"node",
".",
"attr",
"(",
"'y'",
",",
"y",
"(",
"t",
")",
")",
".",
"attr",
"(",
"'height'",
",",
"i",
"(",
"t",
")",
")",
".",
"style",
"(",
"'opacity'",
",",
"j",
"(",
"t",
")",
")",
";",
"}",
"}"
] | Animation tween of vertical bars
@param {obj} d data of bar
@return {void} | [
"Animation",
"tween",
"of",
"vertical",
"bars"
] | 0767051287e9e7211e610b1b13244da71e8e355e | https://github.com/eventbrite/britecharts/blob/0767051287e9e7211e610b1b13244da71e8e355e/src/charts/grouped-bar.js#L804-L814 |
8,552 | AllenFang/react-bootstrap-table | examples/js/cell-edit/cell-edit-classname.js | jobNameValidator | function jobNameValidator(value) {
const response = { isValid: true, notification: { type: 'success', msg: '', title: '' } };
if (!value) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must be inserted';
response.notification.title = 'Requested Value';
} else if (value.length < 10) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must have 10+ characters';
response.notification.title = 'Invalid Value';
}
return response;
} | javascript | function jobNameValidator(value) {
const response = { isValid: true, notification: { type: 'success', msg: '', title: '' } };
if (!value) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must be inserted';
response.notification.title = 'Requested Value';
} else if (value.length < 10) {
response.isValid = false;
response.notification.type = 'error';
response.notification.msg = 'Value must have 10+ characters';
response.notification.title = 'Invalid Value';
}
return response;
} | [
"function",
"jobNameValidator",
"(",
"value",
")",
"{",
"const",
"response",
"=",
"{",
"isValid",
":",
"true",
",",
"notification",
":",
"{",
"type",
":",
"'success'",
",",
"msg",
":",
"''",
",",
"title",
":",
"''",
"}",
"}",
";",
"if",
"(",
"!",
"value",
")",
"{",
"response",
".",
"isValid",
"=",
"false",
";",
"response",
".",
"notification",
".",
"type",
"=",
"'error'",
";",
"response",
".",
"notification",
".",
"msg",
"=",
"'Value must be inserted'",
";",
"response",
".",
"notification",
".",
"title",
"=",
"'Requested Value'",
";",
"}",
"else",
"if",
"(",
"value",
".",
"length",
"<",
"10",
")",
"{",
"response",
".",
"isValid",
"=",
"false",
";",
"response",
".",
"notification",
".",
"type",
"=",
"'error'",
";",
"response",
".",
"notification",
".",
"msg",
"=",
"'Value must have 10+ characters'",
";",
"response",
".",
"notification",
".",
"title",
"=",
"'Invalid Value'",
";",
"}",
"return",
"response",
";",
"}"
] | validator function pass the user input value and should return true|false. | [
"validator",
"function",
"pass",
"the",
"user",
"input",
"value",
"and",
"should",
"return",
"true|false",
"."
] | 26d07defab759e4f9bce22d1d568690830b8d9d7 | https://github.com/AllenFang/react-bootstrap-table/blob/26d07defab759e4f9bce22d1d568690830b8d9d7/examples/js/cell-edit/cell-edit-classname.js#L32-L46 |
8,553 | olistic/warriorjs | packages/warriorjs-helper-get-level-score/src/getClearBonus.js | getClearBonus | function getClearBonus(events, warriorScore, timeBonus) {
const lastEvent = getLastEvent(events);
if (!isFloorClear(lastEvent.floorMap)) {
return 0;
}
return Math.round((warriorScore + timeBonus) * 0.2);
} | javascript | function getClearBonus(events, warriorScore, timeBonus) {
const lastEvent = getLastEvent(events);
if (!isFloorClear(lastEvent.floorMap)) {
return 0;
}
return Math.round((warriorScore + timeBonus) * 0.2);
} | [
"function",
"getClearBonus",
"(",
"events",
",",
"warriorScore",
",",
"timeBonus",
")",
"{",
"const",
"lastEvent",
"=",
"getLastEvent",
"(",
"events",
")",
";",
"if",
"(",
"!",
"isFloorClear",
"(",
"lastEvent",
".",
"floorMap",
")",
")",
"{",
"return",
"0",
";",
"}",
"return",
"Math",
".",
"round",
"(",
"(",
"warriorScore",
"+",
"timeBonus",
")",
"*",
"0.2",
")",
";",
"}"
] | Returns the bonus for clearing the level.
@param {Object[][]} events The events that happened during the play.
@param {number} warriorScore The score of the warrior.
@param {number} timeBonus The time bonus.
@returns {number} The clear bonus. | [
"Returns",
"the",
"bonus",
"for",
"clearing",
"the",
"level",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-helper-get-level-score/src/getClearBonus.js#L13-L20 |
8,554 | olistic/warriorjs | packages/warriorjs-helper-get-level-config/src/index.js | getLevelConfig | function getLevelConfig(tower, levelNumber, warriorName, epic) {
const level = tower.levels[levelNumber - 1];
if (!level) {
return null;
}
const levelConfig = cloneDeep(level);
const levels = epic ? tower.levels : tower.levels.slice(0, levelNumber);
const warriorAbilities = Object.assign(
{},
...levels.map(
({
floor: {
warrior: { abilities },
},
}) => abilities || {},
),
);
levelConfig.number = levelNumber;
levelConfig.floor.warrior.name = warriorName;
levelConfig.floor.warrior.abilities = warriorAbilities;
return levelConfig;
} | javascript | function getLevelConfig(tower, levelNumber, warriorName, epic) {
const level = tower.levels[levelNumber - 1];
if (!level) {
return null;
}
const levelConfig = cloneDeep(level);
const levels = epic ? tower.levels : tower.levels.slice(0, levelNumber);
const warriorAbilities = Object.assign(
{},
...levels.map(
({
floor: {
warrior: { abilities },
},
}) => abilities || {},
),
);
levelConfig.number = levelNumber;
levelConfig.floor.warrior.name = warriorName;
levelConfig.floor.warrior.abilities = warriorAbilities;
return levelConfig;
} | [
"function",
"getLevelConfig",
"(",
"tower",
",",
"levelNumber",
",",
"warriorName",
",",
"epic",
")",
"{",
"const",
"level",
"=",
"tower",
".",
"levels",
"[",
"levelNumber",
"-",
"1",
"]",
";",
"if",
"(",
"!",
"level",
")",
"{",
"return",
"null",
";",
"}",
"const",
"levelConfig",
"=",
"cloneDeep",
"(",
"level",
")",
";",
"const",
"levels",
"=",
"epic",
"?",
"tower",
".",
"levels",
":",
"tower",
".",
"levels",
".",
"slice",
"(",
"0",
",",
"levelNumber",
")",
";",
"const",
"warriorAbilities",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"...",
"levels",
".",
"map",
"(",
"(",
"{",
"floor",
":",
"{",
"warrior",
":",
"{",
"abilities",
"}",
",",
"}",
",",
"}",
")",
"=>",
"abilities",
"||",
"{",
"}",
",",
")",
",",
")",
";",
"levelConfig",
".",
"number",
"=",
"levelNumber",
";",
"levelConfig",
".",
"floor",
".",
"warrior",
".",
"name",
"=",
"warriorName",
";",
"levelConfig",
".",
"floor",
".",
"warrior",
".",
"abilities",
"=",
"warriorAbilities",
";",
"return",
"levelConfig",
";",
"}"
] | Returns the config for the level with the given number.
@param {Object} tower The tower.
@param {number} levelNumber The number of the level.
@param {string} warriorName The name of the warrior.
@param {boolean} epic Whether the level is to be used in epic mode or not.
@returns {Object} The level config. | [
"Returns",
"the",
"config",
"for",
"the",
"level",
"with",
"the",
"given",
"number",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-helper-get-level-config/src/index.js#L13-L37 |
8,555 | olistic/warriorjs | packages/warriorjs-cli/src/parseArgs.js | parseArgs | function parseArgs(args) {
return yargs
.usage('Usage: $0 [options]')
.options({
d: {
alias: 'directory',
default: '.',
describe: 'Run under given directory',
type: 'string',
},
l: {
alias: 'level',
coerce: arg => {
const parsed = Number.parseInt(arg, 10);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: level must be a number');
}
return parsed;
},
describe: 'Practice level (epic mode only)',
type: 'number',
},
s: {
alias: 'silent',
default: false,
describe: 'Suppress play log',
type: 'boolean',
},
t: {
alias: 'time',
coerce: arg => {
const parsed = Number.parseFloat(arg);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: time must be a number');
}
return parsed;
},
default: 0.6,
describe: 'Delay each turn by seconds',
type: 'number',
},
y: {
alias: 'yes',
default: false,
describe: 'Assume yes in non-destructive confirmation dialogs',
type: 'boolean',
},
})
.version()
.help()
.strict()
.parse(args);
} | javascript | function parseArgs(args) {
return yargs
.usage('Usage: $0 [options]')
.options({
d: {
alias: 'directory',
default: '.',
describe: 'Run under given directory',
type: 'string',
},
l: {
alias: 'level',
coerce: arg => {
const parsed = Number.parseInt(arg, 10);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: level must be a number');
}
return parsed;
},
describe: 'Practice level (epic mode only)',
type: 'number',
},
s: {
alias: 'silent',
default: false,
describe: 'Suppress play log',
type: 'boolean',
},
t: {
alias: 'time',
coerce: arg => {
const parsed = Number.parseFloat(arg);
if (Number.isNaN(parsed)) {
throw new Error('Invalid argument: time must be a number');
}
return parsed;
},
default: 0.6,
describe: 'Delay each turn by seconds',
type: 'number',
},
y: {
alias: 'yes',
default: false,
describe: 'Assume yes in non-destructive confirmation dialogs',
type: 'boolean',
},
})
.version()
.help()
.strict()
.parse(args);
} | [
"function",
"parseArgs",
"(",
"args",
")",
"{",
"return",
"yargs",
".",
"usage",
"(",
"'Usage: $0 [options]'",
")",
".",
"options",
"(",
"{",
"d",
":",
"{",
"alias",
":",
"'directory'",
",",
"default",
":",
"'.'",
",",
"describe",
":",
"'Run under given directory'",
",",
"type",
":",
"'string'",
",",
"}",
",",
"l",
":",
"{",
"alias",
":",
"'level'",
",",
"coerce",
":",
"arg",
"=>",
"{",
"const",
"parsed",
"=",
"Number",
".",
"parseInt",
"(",
"arg",
",",
"10",
")",
";",
"if",
"(",
"Number",
".",
"isNaN",
"(",
"parsed",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid argument: level must be a number'",
")",
";",
"}",
"return",
"parsed",
";",
"}",
",",
"describe",
":",
"'Practice level (epic mode only)'",
",",
"type",
":",
"'number'",
",",
"}",
",",
"s",
":",
"{",
"alias",
":",
"'silent'",
",",
"default",
":",
"false",
",",
"describe",
":",
"'Suppress play log'",
",",
"type",
":",
"'boolean'",
",",
"}",
",",
"t",
":",
"{",
"alias",
":",
"'time'",
",",
"coerce",
":",
"arg",
"=>",
"{",
"const",
"parsed",
"=",
"Number",
".",
"parseFloat",
"(",
"arg",
")",
";",
"if",
"(",
"Number",
".",
"isNaN",
"(",
"parsed",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid argument: time must be a number'",
")",
";",
"}",
"return",
"parsed",
";",
"}",
",",
"default",
":",
"0.6",
",",
"describe",
":",
"'Delay each turn by seconds'",
",",
"type",
":",
"'number'",
",",
"}",
",",
"y",
":",
"{",
"alias",
":",
"'yes'",
",",
"default",
":",
"false",
",",
"describe",
":",
"'Assume yes in non-destructive confirmation dialogs'",
",",
"type",
":",
"'boolean'",
",",
"}",
",",
"}",
")",
".",
"version",
"(",
")",
".",
"help",
"(",
")",
".",
"strict",
"(",
")",
".",
"parse",
"(",
"args",
")",
";",
"}"
] | Parses the provided args.
@param {string[]} args The args no parse.
@returns {Object} The parsed args. | [
"Parses",
"the",
"provided",
"args",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/parseArgs.js#L10-L64 |
8,556 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printLogMessage.js | printLogMessage | function printLogMessage(unit, message) {
const prompt = chalk.gray.dim('>');
const logMessage = getUnitStyle(unit)(`${unit.name} ${message}`);
printLine(`${prompt} ${logMessage}`);
} | javascript | function printLogMessage(unit, message) {
const prompt = chalk.gray.dim('>');
const logMessage = getUnitStyle(unit)(`${unit.name} ${message}`);
printLine(`${prompt} ${logMessage}`);
} | [
"function",
"printLogMessage",
"(",
"unit",
",",
"message",
")",
"{",
"const",
"prompt",
"=",
"chalk",
".",
"gray",
".",
"dim",
"(",
"'>'",
")",
";",
"const",
"logMessage",
"=",
"getUnitStyle",
"(",
"unit",
")",
"(",
"`",
"${",
"unit",
".",
"name",
"}",
"${",
"message",
"}",
"`",
")",
";",
"printLine",
"(",
"`",
"${",
"prompt",
"}",
"${",
"logMessage",
"}",
"`",
")",
";",
"}"
] | Prints a message to the log.
@param {Object} unit The unit the message belongs to.
@param {string} message The message to print. | [
"Prints",
"a",
"message",
"to",
"the",
"log",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printLogMessage.js#L12-L16 |
8,557 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printLevelReport.js | printLevelReport | function printLevelReport(
profile,
{ warrior: warriorScore, timeBonus, clearBonus },
totalScore,
grade,
) {
printLine(`Warrior Score: ${warriorScore}`);
printLine(`Time Bonus: ${timeBonus}`);
printLine(`Clear Bonus: ${clearBonus}`);
if (profile.isEpic()) {
printLine(`Level Grade: ${getGradeLetter(grade)}`);
printTotalScore(profile.currentEpicScore, totalScore);
} else {
printTotalScore(profile.score, totalScore);
}
} | javascript | function printLevelReport(
profile,
{ warrior: warriorScore, timeBonus, clearBonus },
totalScore,
grade,
) {
printLine(`Warrior Score: ${warriorScore}`);
printLine(`Time Bonus: ${timeBonus}`);
printLine(`Clear Bonus: ${clearBonus}`);
if (profile.isEpic()) {
printLine(`Level Grade: ${getGradeLetter(grade)}`);
printTotalScore(profile.currentEpicScore, totalScore);
} else {
printTotalScore(profile.score, totalScore);
}
} | [
"function",
"printLevelReport",
"(",
"profile",
",",
"{",
"warrior",
":",
"warriorScore",
",",
"timeBonus",
",",
"clearBonus",
"}",
",",
"totalScore",
",",
"grade",
",",
")",
"{",
"printLine",
"(",
"`",
"${",
"warriorScore",
"}",
"`",
")",
";",
"printLine",
"(",
"`",
"${",
"timeBonus",
"}",
"`",
")",
";",
"printLine",
"(",
"`",
"${",
"clearBonus",
"}",
"`",
")",
";",
"if",
"(",
"profile",
".",
"isEpic",
"(",
")",
")",
"{",
"printLine",
"(",
"`",
"${",
"getGradeLetter",
"(",
"grade",
")",
"}",
"`",
")",
";",
"printTotalScore",
"(",
"profile",
".",
"currentEpicScore",
",",
"totalScore",
")",
";",
"}",
"else",
"{",
"printTotalScore",
"(",
"profile",
".",
"score",
",",
"totalScore",
")",
";",
"}",
"}"
] | Prints the level report.
@param {Profile} profile The profile.
@param {Object} scoreParts The score components.
@param {number} scoreParts.warrior The points earned by the warrior.
@param {number} scoreParts.timeBonus The time bonus.
@param {number} scoreParts.clearBonus The clear bonus.
@param {number} totalScore The total score.
@param {number} grade The grade. | [
"Prints",
"the",
"level",
"report",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printLevelReport.js#L17-L33 |
8,558 | olistic/warriorjs | packages/warriorjs-geography/src/verifyRelativeDirection.js | verifyRelativeDirection | function verifyRelativeDirection(direction) {
if (!RELATIVE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${FORWARD}', '${RIGHT}', '${BACKWARD}' or '${LEFT}'.`,
);
}
} | javascript | function verifyRelativeDirection(direction) {
if (!RELATIVE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${FORWARD}', '${RIGHT}', '${BACKWARD}' or '${LEFT}'.`,
);
}
} | [
"function",
"verifyRelativeDirection",
"(",
"direction",
")",
"{",
"if",
"(",
"!",
"RELATIVE_DIRECTIONS",
".",
"includes",
"(",
"direction",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"direction",
"}",
"${",
"FORWARD",
"}",
"${",
"RIGHT",
"}",
"${",
"BACKWARD",
"}",
"${",
"LEFT",
"}",
"`",
",",
")",
";",
"}",
"}"
] | Checks if the given direction is a valid relative direction.
@param {string} direction The direction.
@throws Will throw if the direction is not valid. | [
"Checks",
"if",
"the",
"given",
"direction",
"is",
"a",
"valid",
"relative",
"direction",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-geography/src/verifyRelativeDirection.js#L16-L22 |
8,559 | olistic/warriorjs | packages/warriorjs-core/src/loadLevel.js | loadAbilities | function loadAbilities(unit, abilities = {}) {
Object.entries(abilities).forEach(([abilityName, abilityCreator]) => {
const ability = abilityCreator(unit);
unit.addAbility(abilityName, ability);
});
} | javascript | function loadAbilities(unit, abilities = {}) {
Object.entries(abilities).forEach(([abilityName, abilityCreator]) => {
const ability = abilityCreator(unit);
unit.addAbility(abilityName, ability);
});
} | [
"function",
"loadAbilities",
"(",
"unit",
",",
"abilities",
"=",
"{",
"}",
")",
"{",
"Object",
".",
"entries",
"(",
"abilities",
")",
".",
"forEach",
"(",
"(",
"[",
"abilityName",
",",
"abilityCreator",
"]",
")",
"=>",
"{",
"const",
"ability",
"=",
"abilityCreator",
"(",
"unit",
")",
";",
"unit",
".",
"addAbility",
"(",
"abilityName",
",",
"ability",
")",
";",
"}",
")",
";",
"}"
] | Loads the abilities onto the unit.
@param {Unit} unit The unit.
@param {Object} abilities The abilities to load. | [
"Loads",
"the",
"abilities",
"onto",
"the",
"unit",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadLevel.js#L13-L18 |
8,560 | olistic/warriorjs | packages/warriorjs-core/src/loadLevel.js | loadEffects | function loadEffects(unit, effects = {}) {
Object.entries(effects).forEach(([effectName, effectCreator]) => {
const effect = effectCreator(unit);
unit.addEffect(effectName, effect);
});
} | javascript | function loadEffects(unit, effects = {}) {
Object.entries(effects).forEach(([effectName, effectCreator]) => {
const effect = effectCreator(unit);
unit.addEffect(effectName, effect);
});
} | [
"function",
"loadEffects",
"(",
"unit",
",",
"effects",
"=",
"{",
"}",
")",
"{",
"Object",
".",
"entries",
"(",
"effects",
")",
".",
"forEach",
"(",
"(",
"[",
"effectName",
",",
"effectCreator",
"]",
")",
"=>",
"{",
"const",
"effect",
"=",
"effectCreator",
"(",
"unit",
")",
";",
"unit",
".",
"addEffect",
"(",
"effectName",
",",
"effect",
")",
";",
"}",
")",
";",
"}"
] | Loads the effects onto the unit.
@param {Unit} unit The unit.
@param {Object} effects The effects to load. | [
"Loads",
"the",
"effects",
"onto",
"the",
"unit",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadLevel.js#L26-L31 |
8,561 | olistic/warriorjs | packages/warriorjs-core/src/loadLevel.js | loadWarrior | function loadWarrior(
{ name, character, color, maxHealth, abilities, effects, position },
floor,
playerCode,
) {
const warrior = new Warrior(name, character, color, maxHealth);
loadAbilities(warrior, abilities);
loadEffects(warrior, effects);
warrior.playTurn = playerCode ? loadPlayer(playerCode) : () => {};
floor.addWarrior(warrior, position);
} | javascript | function loadWarrior(
{ name, character, color, maxHealth, abilities, effects, position },
floor,
playerCode,
) {
const warrior = new Warrior(name, character, color, maxHealth);
loadAbilities(warrior, abilities);
loadEffects(warrior, effects);
warrior.playTurn = playerCode ? loadPlayer(playerCode) : () => {};
floor.addWarrior(warrior, position);
} | [
"function",
"loadWarrior",
"(",
"{",
"name",
",",
"character",
",",
"color",
",",
"maxHealth",
",",
"abilities",
",",
"effects",
",",
"position",
"}",
",",
"floor",
",",
"playerCode",
",",
")",
"{",
"const",
"warrior",
"=",
"new",
"Warrior",
"(",
"name",
",",
"character",
",",
"color",
",",
"maxHealth",
")",
";",
"loadAbilities",
"(",
"warrior",
",",
"abilities",
")",
";",
"loadEffects",
"(",
"warrior",
",",
"effects",
")",
";",
"warrior",
".",
"playTurn",
"=",
"playerCode",
"?",
"loadPlayer",
"(",
"playerCode",
")",
":",
"(",
")",
"=>",
"{",
"}",
";",
"floor",
".",
"addWarrior",
"(",
"warrior",
",",
"position",
")",
";",
"}"
] | Loads the warrior.
@param {Object} warriorConfig The config of the warrior.
@param {Floor} floor The floor of the level.
@param {string} [playerCode] The code of the player. | [
"Loads",
"the",
"warrior",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadLevel.js#L40-L50 |
8,562 | olistic/warriorjs | packages/warriorjs-core/src/loadLevel.js | loadUnit | function loadUnit(
{
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
abilities,
effects,
playTurn,
position,
},
floor,
) {
const unit = new Unit(
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
);
loadAbilities(unit, abilities);
loadEffects(unit, effects);
unit.playTurn = playTurn;
floor.addUnit(unit, position);
} | javascript | function loadUnit(
{
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
abilities,
effects,
playTurn,
position,
},
floor,
) {
const unit = new Unit(
name,
character,
color,
maxHealth,
reward,
enemy,
bound,
);
loadAbilities(unit, abilities);
loadEffects(unit, effects);
unit.playTurn = playTurn;
floor.addUnit(unit, position);
} | [
"function",
"loadUnit",
"(",
"{",
"name",
",",
"character",
",",
"color",
",",
"maxHealth",
",",
"reward",
",",
"enemy",
",",
"bound",
",",
"abilities",
",",
"effects",
",",
"playTurn",
",",
"position",
",",
"}",
",",
"floor",
",",
")",
"{",
"const",
"unit",
"=",
"new",
"Unit",
"(",
"name",
",",
"character",
",",
"color",
",",
"maxHealth",
",",
"reward",
",",
"enemy",
",",
"bound",
",",
")",
";",
"loadAbilities",
"(",
"unit",
",",
"abilities",
")",
";",
"loadEffects",
"(",
"unit",
",",
"effects",
")",
";",
"unit",
".",
"playTurn",
"=",
"playTurn",
";",
"floor",
".",
"addUnit",
"(",
"unit",
",",
"position",
")",
";",
"}"
] | Loads a unit.
@param {Object} unitConfig The config of the unit.
@param {Floor} floor The floor of the level. | [
"Loads",
"a",
"unit",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadLevel.js#L58-L87 |
8,563 | olistic/warriorjs | packages/warriorjs-core/src/loadLevel.js | loadLevel | function loadLevel(
{
number,
description,
tip,
clue,
floor: { size, stairs, warrior, units = [] },
},
playerCode,
) {
const { width, height } = size;
const stairsLocation = [stairs.x, stairs.y];
const floor = new Floor(width, height, stairsLocation);
loadWarrior(warrior, floor, playerCode);
units.forEach(unit => loadUnit(unit, floor));
return new Level(number, description, tip, clue, floor);
} | javascript | function loadLevel(
{
number,
description,
tip,
clue,
floor: { size, stairs, warrior, units = [] },
},
playerCode,
) {
const { width, height } = size;
const stairsLocation = [stairs.x, stairs.y];
const floor = new Floor(width, height, stairsLocation);
loadWarrior(warrior, floor, playerCode);
units.forEach(unit => loadUnit(unit, floor));
return new Level(number, description, tip, clue, floor);
} | [
"function",
"loadLevel",
"(",
"{",
"number",
",",
"description",
",",
"tip",
",",
"clue",
",",
"floor",
":",
"{",
"size",
",",
"stairs",
",",
"warrior",
",",
"units",
"=",
"[",
"]",
"}",
",",
"}",
",",
"playerCode",
",",
")",
"{",
"const",
"{",
"width",
",",
"height",
"}",
"=",
"size",
";",
"const",
"stairsLocation",
"=",
"[",
"stairs",
".",
"x",
",",
"stairs",
".",
"y",
"]",
";",
"const",
"floor",
"=",
"new",
"Floor",
"(",
"width",
",",
"height",
",",
"stairsLocation",
")",
";",
"loadWarrior",
"(",
"warrior",
",",
"floor",
",",
"playerCode",
")",
";",
"units",
".",
"forEach",
"(",
"unit",
"=>",
"loadUnit",
"(",
"unit",
",",
"floor",
")",
")",
";",
"return",
"new",
"Level",
"(",
"number",
",",
"description",
",",
"tip",
",",
"clue",
",",
"floor",
")",
";",
"}"
] | Loads a level from a level config.
@param {Object} levelConfig The config of the level.
@param {string} [playerCode] The code of the player.
@returns {Level} The loaded level. | [
"Loads",
"a",
"level",
"from",
"a",
"level",
"config",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadLevel.js#L97-L115 |
8,564 | olistic/warriorjs | packages/warriorjs-cli/src/ui/requestConfirmation.js | requestConfirmation | async function requestConfirmation(message, defaultAnswer = false) {
const answerName = 'requestConfirmation';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'confirm',
default: defaultAnswer,
},
]);
return answers[answerName];
} | javascript | async function requestConfirmation(message, defaultAnswer = false) {
const answerName = 'requestConfirmation';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'confirm',
default: defaultAnswer,
},
]);
return answers[answerName];
} | [
"async",
"function",
"requestConfirmation",
"(",
"message",
",",
"defaultAnswer",
"=",
"false",
")",
"{",
"const",
"answerName",
"=",
"'requestConfirmation'",
";",
"const",
"answers",
"=",
"await",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"message",
",",
"name",
":",
"answerName",
",",
"type",
":",
"'confirm'",
",",
"default",
":",
"defaultAnswer",
",",
"}",
",",
"]",
")",
";",
"return",
"answers",
"[",
"answerName",
"]",
";",
"}"
] | Requests confirmation from the user.
@param {string} message The prompt message.
@param {boolean} defaultAnswer The default answer. | [
"Requests",
"confirmation",
"from",
"the",
"user",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/requestConfirmation.js#L9-L20 |
8,565 | olistic/warriorjs | packages/warriorjs-geography/src/verifyAbsoluteDirection.js | verifyAbsoluteDirection | function verifyAbsoluteDirection(direction) {
if (!ABSOLUTE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${NORTH}', '${EAST}', '${SOUTH}' or '${WEST}'.`,
);
}
} | javascript | function verifyAbsoluteDirection(direction) {
if (!ABSOLUTE_DIRECTIONS.includes(direction)) {
throw new Error(
`Unknown direction: '${direction}'. Should be one of: '${NORTH}', '${EAST}', '${SOUTH}' or '${WEST}'.`,
);
}
} | [
"function",
"verifyAbsoluteDirection",
"(",
"direction",
")",
"{",
"if",
"(",
"!",
"ABSOLUTE_DIRECTIONS",
".",
"includes",
"(",
"direction",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"`",
"${",
"direction",
"}",
"${",
"NORTH",
"}",
"${",
"EAST",
"}",
"${",
"SOUTH",
"}",
"${",
"WEST",
"}",
"`",
",",
")",
";",
"}",
"}"
] | Checks if the given direction is a valid absolute direction.
@param {string} direction The direction.
@throws Will throw if the direction is not valid. | [
"Checks",
"if",
"the",
"given",
"direction",
"is",
"a",
"valid",
"absolute",
"direction",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-geography/src/verifyAbsoluteDirection.js#L16-L22 |
8,566 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printTurnHeader.js | printTurnHeader | function printTurnHeader(turnNumber) {
printRow(chalk.gray.dim(` ${String(turnNumber).padStart(3, '0')} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | javascript | function printTurnHeader(turnNumber) {
printRow(chalk.gray.dim(` ${String(turnNumber).padStart(3, '0')} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | [
"function",
"printTurnHeader",
"(",
"turnNumber",
")",
"{",
"printRow",
"(",
"chalk",
".",
"gray",
".",
"dim",
"(",
"`",
"${",
"String",
"(",
"turnNumber",
")",
".",
"padStart",
"(",
"3",
",",
"'0'",
")",
"}",
"`",
")",
",",
"{",
"position",
":",
"'middle'",
",",
"padding",
":",
"chalk",
".",
"gray",
".",
"dim",
"(",
"'~'",
")",
",",
"}",
")",
";",
"}"
] | Prints the turn header.
@param {number} turnNumber The turn number. | [
"Prints",
"the",
"turn",
"header",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printTurnHeader.js#L10-L15 |
8,567 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printFloorMap.js | printFloorMap | function printFloorMap(floorMap) {
printLine(
floorMap
.map(row =>
row
.map(({ character, unit }) => {
if (unit) {
return getUnitStyle(unit)(character);
}
return character;
})
.join(''),
)
.join('\n'),
);
} | javascript | function printFloorMap(floorMap) {
printLine(
floorMap
.map(row =>
row
.map(({ character, unit }) => {
if (unit) {
return getUnitStyle(unit)(character);
}
return character;
})
.join(''),
)
.join('\n'),
);
} | [
"function",
"printFloorMap",
"(",
"floorMap",
")",
"{",
"printLine",
"(",
"floorMap",
".",
"map",
"(",
"row",
"=>",
"row",
".",
"map",
"(",
"(",
"{",
"character",
",",
"unit",
"}",
")",
"=>",
"{",
"if",
"(",
"unit",
")",
"{",
"return",
"getUnitStyle",
"(",
"unit",
")",
"(",
"character",
")",
";",
"}",
"return",
"character",
";",
"}",
")",
".",
"join",
"(",
"''",
")",
",",
")",
".",
"join",
"(",
"'\\n'",
")",
",",
")",
";",
"}"
] | Prints the floor map.
@param {Object[][]} floorMap The map of the floor. | [
"Prints",
"the",
"floor",
"map",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printFloorMap.js#L9-L25 |
8,568 | olistic/warriorjs | packages/warriorjs-core/src/loadPlayer.js | loadPlayer | function loadPlayer(playerCode) {
const sandbox = vm.createContext();
// Do not collect stack frames for errors in the player code.
vm.runInContext('Error.stackTraceLimit = 0;', sandbox);
try {
vm.runInContext(playerCode, sandbox, {
filename: playerCodeFilename,
timeout: playerCodeTimeout,
});
} catch (err) {
const error = new Error(`Check your syntax and try again!\n\n${err.stack}`);
error.code = 'InvalidPlayerCode';
throw error;
}
try {
const player = vm.runInContext('new Player();', sandbox, {
timeout: playerCodeTimeout,
});
assert(typeof player.playTurn === 'function', 'playTurn is not defined');
const playTurn = turn => {
try {
player.playTurn(turn);
} catch (err) {
const error = new Error(err.message);
error.code = 'InvalidPlayerCode';
throw error;
}
};
return playTurn;
} catch (err) {
if (err.message === 'Player is not defined') {
const error = new Error('You must define a Player class!');
error.code = 'InvalidPlayerCode';
throw error;
} else if (err.message === 'playTurn is not defined') {
const error = new Error(
'Your Player class must define a playTurn method!',
);
error.code = 'InvalidPlayerCode';
throw error;
}
throw err;
}
} | javascript | function loadPlayer(playerCode) {
const sandbox = vm.createContext();
// Do not collect stack frames for errors in the player code.
vm.runInContext('Error.stackTraceLimit = 0;', sandbox);
try {
vm.runInContext(playerCode, sandbox, {
filename: playerCodeFilename,
timeout: playerCodeTimeout,
});
} catch (err) {
const error = new Error(`Check your syntax and try again!\n\n${err.stack}`);
error.code = 'InvalidPlayerCode';
throw error;
}
try {
const player = vm.runInContext('new Player();', sandbox, {
timeout: playerCodeTimeout,
});
assert(typeof player.playTurn === 'function', 'playTurn is not defined');
const playTurn = turn => {
try {
player.playTurn(turn);
} catch (err) {
const error = new Error(err.message);
error.code = 'InvalidPlayerCode';
throw error;
}
};
return playTurn;
} catch (err) {
if (err.message === 'Player is not defined') {
const error = new Error('You must define a Player class!');
error.code = 'InvalidPlayerCode';
throw error;
} else if (err.message === 'playTurn is not defined') {
const error = new Error(
'Your Player class must define a playTurn method!',
);
error.code = 'InvalidPlayerCode';
throw error;
}
throw err;
}
} | [
"function",
"loadPlayer",
"(",
"playerCode",
")",
"{",
"const",
"sandbox",
"=",
"vm",
".",
"createContext",
"(",
")",
";",
"// Do not collect stack frames for errors in the player code.",
"vm",
".",
"runInContext",
"(",
"'Error.stackTraceLimit = 0;'",
",",
"sandbox",
")",
";",
"try",
"{",
"vm",
".",
"runInContext",
"(",
"playerCode",
",",
"sandbox",
",",
"{",
"filename",
":",
"playerCodeFilename",
",",
"timeout",
":",
"playerCodeTimeout",
",",
"}",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"`",
"\\n",
"\\n",
"${",
"err",
".",
"stack",
"}",
"`",
")",
";",
"error",
".",
"code",
"=",
"'InvalidPlayerCode'",
";",
"throw",
"error",
";",
"}",
"try",
"{",
"const",
"player",
"=",
"vm",
".",
"runInContext",
"(",
"'new Player();'",
",",
"sandbox",
",",
"{",
"timeout",
":",
"playerCodeTimeout",
",",
"}",
")",
";",
"assert",
"(",
"typeof",
"player",
".",
"playTurn",
"===",
"'function'",
",",
"'playTurn is not defined'",
")",
";",
"const",
"playTurn",
"=",
"turn",
"=>",
"{",
"try",
"{",
"player",
".",
"playTurn",
"(",
"turn",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"err",
".",
"message",
")",
";",
"error",
".",
"code",
"=",
"'InvalidPlayerCode'",
";",
"throw",
"error",
";",
"}",
"}",
";",
"return",
"playTurn",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"if",
"(",
"err",
".",
"message",
"===",
"'Player is not defined'",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"'You must define a Player class!'",
")",
";",
"error",
".",
"code",
"=",
"'InvalidPlayerCode'",
";",
"throw",
"error",
";",
"}",
"else",
"if",
"(",
"err",
".",
"message",
"===",
"'playTurn is not defined'",
")",
"{",
"const",
"error",
"=",
"new",
"Error",
"(",
"'Your Player class must define a playTurn method!'",
",",
")",
";",
"error",
".",
"code",
"=",
"'InvalidPlayerCode'",
";",
"throw",
"error",
";",
"}",
"throw",
"err",
";",
"}",
"}"
] | Loads the player code and returns the playTurn function.
@param {string} playerCode The code of the player.
@returns {Function} The playTurn function. | [
"Loads",
"the",
"player",
"code",
"and",
"returns",
"the",
"playTurn",
"function",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/loadPlayer.js#L14-L61 |
8,569 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printRow.js | printRow | function printRow(message, { position = 'start', padding = ' ' } = {}) {
const [screenWidth] = getScreenSize();
const rowWidth = screenWidth - 1; // Consider line break length.
const messageWidth = stringWidth(message);
const paddingWidth = (rowWidth - messageWidth) / 2;
const startPadding = padding.repeat(Math.floor(paddingWidth));
const endPadding = padding.repeat(Math.ceil(paddingWidth));
if (position === 'start') {
printLine(`${message}${startPadding}${endPadding}`);
} else if (position === 'middle') {
printLine(`${startPadding}${message}${endPadding}`);
} else if (position === 'end') {
printLine(`${startPadding}${endPadding}${message}`);
}
} | javascript | function printRow(message, { position = 'start', padding = ' ' } = {}) {
const [screenWidth] = getScreenSize();
const rowWidth = screenWidth - 1; // Consider line break length.
const messageWidth = stringWidth(message);
const paddingWidth = (rowWidth - messageWidth) / 2;
const startPadding = padding.repeat(Math.floor(paddingWidth));
const endPadding = padding.repeat(Math.ceil(paddingWidth));
if (position === 'start') {
printLine(`${message}${startPadding}${endPadding}`);
} else if (position === 'middle') {
printLine(`${startPadding}${message}${endPadding}`);
} else if (position === 'end') {
printLine(`${startPadding}${endPadding}${message}`);
}
} | [
"function",
"printRow",
"(",
"message",
",",
"{",
"position",
"=",
"'start'",
",",
"padding",
"=",
"' '",
"}",
"=",
"{",
"}",
")",
"{",
"const",
"[",
"screenWidth",
"]",
"=",
"getScreenSize",
"(",
")",
";",
"const",
"rowWidth",
"=",
"screenWidth",
"-",
"1",
";",
"// Consider line break length.",
"const",
"messageWidth",
"=",
"stringWidth",
"(",
"message",
")",
";",
"const",
"paddingWidth",
"=",
"(",
"rowWidth",
"-",
"messageWidth",
")",
"/",
"2",
";",
"const",
"startPadding",
"=",
"padding",
".",
"repeat",
"(",
"Math",
".",
"floor",
"(",
"paddingWidth",
")",
")",
";",
"const",
"endPadding",
"=",
"padding",
".",
"repeat",
"(",
"Math",
".",
"ceil",
"(",
"paddingWidth",
")",
")",
";",
"if",
"(",
"position",
"===",
"'start'",
")",
"{",
"printLine",
"(",
"`",
"${",
"message",
"}",
"${",
"startPadding",
"}",
"${",
"endPadding",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"position",
"===",
"'middle'",
")",
"{",
"printLine",
"(",
"`",
"${",
"startPadding",
"}",
"${",
"message",
"}",
"${",
"endPadding",
"}",
"`",
")",
";",
"}",
"else",
"if",
"(",
"position",
"===",
"'end'",
")",
"{",
"printLine",
"(",
"`",
"${",
"startPadding",
"}",
"${",
"endPadding",
"}",
"${",
"message",
"}",
"`",
")",
";",
"}",
"}"
] | Prints a message and fills the rest of the line with a padding character.
@param {string} message The message to print.
@param {Object} options The options.
@param {string} options.position The position of the message.
@param {string} options.padding The padding character. | [
"Prints",
"a",
"message",
"and",
"fills",
"the",
"rest",
"of",
"the",
"line",
"with",
"a",
"padding",
"character",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printRow.js#L14-L28 |
8,570 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printTowerReport.js | printTowerReport | function printTowerReport(profile) {
const averageGrade = profile.calculateAverageGrade();
if (!averageGrade) {
return;
}
const averageGradeLetter = getGradeLetter(averageGrade);
printLine(`Your average grade for this tower is: ${averageGradeLetter}\n`);
Object.keys(profile.currentEpicGrades)
.sort()
.forEach(levelNumber => {
const grade = profile.currentEpicGrades[levelNumber];
const gradeLetter = getGradeLetter(grade);
printLine(` Level ${levelNumber}: ${gradeLetter}`);
});
printLine('\nTo practice a level, use the -l option.');
} | javascript | function printTowerReport(profile) {
const averageGrade = profile.calculateAverageGrade();
if (!averageGrade) {
return;
}
const averageGradeLetter = getGradeLetter(averageGrade);
printLine(`Your average grade for this tower is: ${averageGradeLetter}\n`);
Object.keys(profile.currentEpicGrades)
.sort()
.forEach(levelNumber => {
const grade = profile.currentEpicGrades[levelNumber];
const gradeLetter = getGradeLetter(grade);
printLine(` Level ${levelNumber}: ${gradeLetter}`);
});
printLine('\nTo practice a level, use the -l option.');
} | [
"function",
"printTowerReport",
"(",
"profile",
")",
"{",
"const",
"averageGrade",
"=",
"profile",
".",
"calculateAverageGrade",
"(",
")",
";",
"if",
"(",
"!",
"averageGrade",
")",
"{",
"return",
";",
"}",
"const",
"averageGradeLetter",
"=",
"getGradeLetter",
"(",
"averageGrade",
")",
";",
"printLine",
"(",
"`",
"${",
"averageGradeLetter",
"}",
"\\n",
"`",
")",
";",
"Object",
".",
"keys",
"(",
"profile",
".",
"currentEpicGrades",
")",
".",
"sort",
"(",
")",
".",
"forEach",
"(",
"levelNumber",
"=>",
"{",
"const",
"grade",
"=",
"profile",
".",
"currentEpicGrades",
"[",
"levelNumber",
"]",
";",
"const",
"gradeLetter",
"=",
"getGradeLetter",
"(",
"grade",
")",
";",
"printLine",
"(",
"`",
"${",
"levelNumber",
"}",
"${",
"gradeLetter",
"}",
"`",
")",
";",
"}",
")",
";",
"printLine",
"(",
"'\\nTo practice a level, use the -l option.'",
")",
";",
"}"
] | Prints the tower report.
@param {Profile} profile The profile. | [
"Prints",
"the",
"tower",
"report",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printTowerReport.js#L10-L28 |
8,571 | olistic/warriorjs | packages/warriorjs-helper-get-level-score/src/index.js | getLevelScore | function getLevelScore({ passed, events }, { timeBonus }) {
if (!passed) {
return null;
}
const warriorScore = getWarriorScore(events);
const remainingTimeBonus = getRemainingTimeBonus(events, timeBonus);
const clearBonus = getClearBonus(events, warriorScore, remainingTimeBonus);
return {
clearBonus,
timeBonus: remainingTimeBonus,
warrior: warriorScore,
};
} | javascript | function getLevelScore({ passed, events }, { timeBonus }) {
if (!passed) {
return null;
}
const warriorScore = getWarriorScore(events);
const remainingTimeBonus = getRemainingTimeBonus(events, timeBonus);
const clearBonus = getClearBonus(events, warriorScore, remainingTimeBonus);
return {
clearBonus,
timeBonus: remainingTimeBonus,
warrior: warriorScore,
};
} | [
"function",
"getLevelScore",
"(",
"{",
"passed",
",",
"events",
"}",
",",
"{",
"timeBonus",
"}",
")",
"{",
"if",
"(",
"!",
"passed",
")",
"{",
"return",
"null",
";",
"}",
"const",
"warriorScore",
"=",
"getWarriorScore",
"(",
"events",
")",
";",
"const",
"remainingTimeBonus",
"=",
"getRemainingTimeBonus",
"(",
"events",
",",
"timeBonus",
")",
";",
"const",
"clearBonus",
"=",
"getClearBonus",
"(",
"events",
",",
"warriorScore",
",",
"remainingTimeBonus",
")",
";",
"return",
"{",
"clearBonus",
",",
"timeBonus",
":",
"remainingTimeBonus",
",",
"warrior",
":",
"warriorScore",
",",
"}",
";",
"}"
] | Returns the score for the given level.
@param {Object} result The level result.
@param {boolean} result.passed Whether the level was passed or not.
@param {Object[][]} result.events The events of the level.
@param {Object} levelConfig The level config.
@param {number} levelConfig.timeBonus The bonus for passing the level in time.
@returns {Object} The score of the level, broken down into its components. | [
"Returns",
"the",
"score",
"for",
"the",
"given",
"level",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-helper-get-level-score/src/index.js#L16-L29 |
8,572 | olistic/warriorjs | packages/warriorjs-cli/src/loadTowers.js | getExternalTowersInfo | function getExternalTowersInfo() {
const cliDir = findUp.sync('@warriorjs/cli', { cwd: __dirname });
if (!cliDir) {
return [];
}
const cliParentDir = path.resolve(cliDir, '..');
const towerSearchDir = findUp.sync('node_modules', { cwd: cliParentDir });
const towerPackageJsonPaths = globby.sync(
[officialTowerPackageJsonPattern, communityTowerPackageJsonPattern],
{ cwd: towerSearchDir },
);
const towerPackageNames = towerPackageJsonPaths.map(path.dirname);
return towerPackageNames.map(towerPackageName => ({
id: getTowerId(towerPackageName),
requirePath: resolve.sync(towerPackageName, { basedir: towerSearchDir }),
}));
} | javascript | function getExternalTowersInfo() {
const cliDir = findUp.sync('@warriorjs/cli', { cwd: __dirname });
if (!cliDir) {
return [];
}
const cliParentDir = path.resolve(cliDir, '..');
const towerSearchDir = findUp.sync('node_modules', { cwd: cliParentDir });
const towerPackageJsonPaths = globby.sync(
[officialTowerPackageJsonPattern, communityTowerPackageJsonPattern],
{ cwd: towerSearchDir },
);
const towerPackageNames = towerPackageJsonPaths.map(path.dirname);
return towerPackageNames.map(towerPackageName => ({
id: getTowerId(towerPackageName),
requirePath: resolve.sync(towerPackageName, { basedir: towerSearchDir }),
}));
} | [
"function",
"getExternalTowersInfo",
"(",
")",
"{",
"const",
"cliDir",
"=",
"findUp",
".",
"sync",
"(",
"'@warriorjs/cli'",
",",
"{",
"cwd",
":",
"__dirname",
"}",
")",
";",
"if",
"(",
"!",
"cliDir",
")",
"{",
"return",
"[",
"]",
";",
"}",
"const",
"cliParentDir",
"=",
"path",
".",
"resolve",
"(",
"cliDir",
",",
"'..'",
")",
";",
"const",
"towerSearchDir",
"=",
"findUp",
".",
"sync",
"(",
"'node_modules'",
",",
"{",
"cwd",
":",
"cliParentDir",
"}",
")",
";",
"const",
"towerPackageJsonPaths",
"=",
"globby",
".",
"sync",
"(",
"[",
"officialTowerPackageJsonPattern",
",",
"communityTowerPackageJsonPattern",
"]",
",",
"{",
"cwd",
":",
"towerSearchDir",
"}",
",",
")",
";",
"const",
"towerPackageNames",
"=",
"towerPackageJsonPaths",
".",
"map",
"(",
"path",
".",
"dirname",
")",
";",
"return",
"towerPackageNames",
".",
"map",
"(",
"towerPackageName",
"=>",
"(",
"{",
"id",
":",
"getTowerId",
"(",
"towerPackageName",
")",
",",
"requirePath",
":",
"resolve",
".",
"sync",
"(",
"towerPackageName",
",",
"{",
"basedir",
":",
"towerSearchDir",
"}",
")",
",",
"}",
")",
")",
";",
"}"
] | Returns the external towers info.
It searches for official and community towers installed in the nearest
`node_modules` directory that is parent to @warriorjs/cli.
@returns {Object[]} The external towers info. | [
"Returns",
"the",
"external",
"towers",
"info",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/loadTowers.js#L36-L53 |
8,573 | olistic/warriorjs | packages/warriorjs-cli/src/loadTowers.js | loadTowers | function loadTowers() {
const internalTowersInfo = getInternalTowersInfo();
const externalTowersInfo = getExternalTowersInfo();
return uniqBy(internalTowersInfo.concat(externalTowersInfo), 'id').map(
({ id, requirePath }) => {
const { name, description, levels } = require(requirePath); // eslint-disable-line global-require, import/no-dynamic-require
return new Tower(id, name, description, levels);
},
);
} | javascript | function loadTowers() {
const internalTowersInfo = getInternalTowersInfo();
const externalTowersInfo = getExternalTowersInfo();
return uniqBy(internalTowersInfo.concat(externalTowersInfo), 'id').map(
({ id, requirePath }) => {
const { name, description, levels } = require(requirePath); // eslint-disable-line global-require, import/no-dynamic-require
return new Tower(id, name, description, levels);
},
);
} | [
"function",
"loadTowers",
"(",
")",
"{",
"const",
"internalTowersInfo",
"=",
"getInternalTowersInfo",
"(",
")",
";",
"const",
"externalTowersInfo",
"=",
"getExternalTowersInfo",
"(",
")",
";",
"return",
"uniqBy",
"(",
"internalTowersInfo",
".",
"concat",
"(",
"externalTowersInfo",
")",
",",
"'id'",
")",
".",
"map",
"(",
"(",
"{",
"id",
",",
"requirePath",
"}",
")",
"=>",
"{",
"const",
"{",
"name",
",",
"description",
",",
"levels",
"}",
"=",
"require",
"(",
"requirePath",
")",
";",
"// eslint-disable-line global-require, import/no-dynamic-require",
"return",
"new",
"Tower",
"(",
"id",
",",
"name",
",",
"description",
",",
"levels",
")",
";",
"}",
",",
")",
";",
"}"
] | Loads the installed towers.
@returns {Tower[]} The loaded towers. | [
"Loads",
"the",
"installed",
"towers",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/loadTowers.js#L60-L69 |
8,574 | olistic/warriorjs | packages/warriorjs-geography/src/rotateRelativeOffset.js | rotateRelativeOffset | function rotateRelativeOffset([forward, right], direction) {
verifyRelativeDirection(direction);
if (direction === FORWARD) {
return [forward, right];
}
if (direction === RIGHT) {
return [-right, forward];
}
if (direction === BACKWARD) {
return [-forward, -right];
}
return [right, -forward];
} | javascript | function rotateRelativeOffset([forward, right], direction) {
verifyRelativeDirection(direction);
if (direction === FORWARD) {
return [forward, right];
}
if (direction === RIGHT) {
return [-right, forward];
}
if (direction === BACKWARD) {
return [-forward, -right];
}
return [right, -forward];
} | [
"function",
"rotateRelativeOffset",
"(",
"[",
"forward",
",",
"right",
"]",
",",
"direction",
")",
"{",
"verifyRelativeDirection",
"(",
"direction",
")",
";",
"if",
"(",
"direction",
"===",
"FORWARD",
")",
"{",
"return",
"[",
"forward",
",",
"right",
"]",
";",
"}",
"if",
"(",
"direction",
"===",
"RIGHT",
")",
"{",
"return",
"[",
"-",
"right",
",",
"forward",
"]",
";",
"}",
"if",
"(",
"direction",
"===",
"BACKWARD",
")",
"{",
"return",
"[",
"-",
"forward",
",",
"-",
"right",
"]",
";",
"}",
"return",
"[",
"right",
",",
"-",
"forward",
"]",
";",
"}"
] | Rotates the given relative offset in the given direction.
@param {number[]} offset The relative offset as [forward, right].
@param {string} direction The direction (relative direction).
@returns {number[]} The rotated offset as [forward, right]. | [
"Rotates",
"the",
"given",
"relative",
"offset",
"in",
"the",
"given",
"direction",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-geography/src/rotateRelativeOffset.js#L12-L28 |
8,575 | olistic/warriorjs | packages/warriorjs-cli/src/ui/requestChoice.js | requestChoice | async function requestChoice(message, items) {
const answerName = 'requestChoice';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'list',
choices: getChoices(items),
},
]);
return answers[answerName];
} | javascript | async function requestChoice(message, items) {
const answerName = 'requestChoice';
const answers = await inquirer.prompt([
{
message,
name: answerName,
type: 'list',
choices: getChoices(items),
},
]);
return answers[answerName];
} | [
"async",
"function",
"requestChoice",
"(",
"message",
",",
"items",
")",
"{",
"const",
"answerName",
"=",
"'requestChoice'",
";",
"const",
"answers",
"=",
"await",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"message",
",",
"name",
":",
"answerName",
",",
"type",
":",
"'list'",
",",
"choices",
":",
"getChoices",
"(",
"items",
")",
",",
"}",
",",
"]",
")",
";",
"return",
"answers",
"[",
"answerName",
"]",
";",
"}"
] | Requests a selection of one of the given items from the user.
@param {string} message The prompt message.
@param {any[]} items The items to choose from. | [
"Requests",
"a",
"selection",
"of",
"one",
"of",
"the",
"given",
"items",
"from",
"the",
"user",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/requestChoice.js#L25-L36 |
8,576 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printBoard.js | printBoard | function printBoard(floorMap, warriorStatus, offset) {
if (offset > 0) {
const floorMapRows = floorMap.length;
print(ansiEscapes.cursorUp(offset + floorMapRows + warriorStatusRows));
}
printWarriorStatus(warriorStatus);
printFloorMap(floorMap);
if (offset > 0) {
print(ansiEscapes.cursorDown(offset));
}
} | javascript | function printBoard(floorMap, warriorStatus, offset) {
if (offset > 0) {
const floorMapRows = floorMap.length;
print(ansiEscapes.cursorUp(offset + floorMapRows + warriorStatusRows));
}
printWarriorStatus(warriorStatus);
printFloorMap(floorMap);
if (offset > 0) {
print(ansiEscapes.cursorDown(offset));
}
} | [
"function",
"printBoard",
"(",
"floorMap",
",",
"warriorStatus",
",",
"offset",
")",
"{",
"if",
"(",
"offset",
">",
"0",
")",
"{",
"const",
"floorMapRows",
"=",
"floorMap",
".",
"length",
";",
"print",
"(",
"ansiEscapes",
".",
"cursorUp",
"(",
"offset",
"+",
"floorMapRows",
"+",
"warriorStatusRows",
")",
")",
";",
"}",
"printWarriorStatus",
"(",
"warriorStatus",
")",
";",
"printFloorMap",
"(",
"floorMap",
")",
";",
"if",
"(",
"offset",
">",
"0",
")",
"{",
"print",
"(",
"ansiEscapes",
".",
"cursorDown",
"(",
"offset",
")",
")",
";",
"}",
"}"
] | Prints the game board after moving the cursor up a given number of rows.
@param {Object[][]} floorMap The map of the floor.
@param {Object} warriorStatus The status of the warrior.
@param {number} offset The number of rows. | [
"Prints",
"the",
"game",
"board",
"after",
"moving",
"the",
"cursor",
"up",
"a",
"given",
"number",
"of",
"rows",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printBoard.js#L16-L28 |
8,577 | olistic/warriorjs | packages/warriorjs-helper-get-level-score/src/getRemainingTimeBonus.js | getRemainingTimeBonus | function getRemainingTimeBonus(events, timeBonus) {
const turnCount = getTurnCount(events);
const remainingTimeBonus = timeBonus - turnCount;
return Math.max(remainingTimeBonus, 0);
} | javascript | function getRemainingTimeBonus(events, timeBonus) {
const turnCount = getTurnCount(events);
const remainingTimeBonus = timeBonus - turnCount;
return Math.max(remainingTimeBonus, 0);
} | [
"function",
"getRemainingTimeBonus",
"(",
"events",
",",
"timeBonus",
")",
"{",
"const",
"turnCount",
"=",
"getTurnCount",
"(",
"events",
")",
";",
"const",
"remainingTimeBonus",
"=",
"timeBonus",
"-",
"turnCount",
";",
"return",
"Math",
".",
"max",
"(",
"remainingTimeBonus",
",",
"0",
")",
";",
"}"
] | Returns the remaining time bonus.
@param {Object[][]} events The events that happened during the play.
@param {number} timeBonus The initial time bonus.
@returns {number} The time bonus. | [
"Returns",
"the",
"remaining",
"time",
"bonus",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-helper-get-level-score/src/getRemainingTimeBonus.js#L11-L15 |
8,578 | olistic/warriorjs | packages/warriorjs-cli/src/ui/requestInput.js | requestInput | async function requestInput(message, suggestions = []) {
const answerName = 'requestInput';
const answers = await inquirer.prompt([
{
message,
suggestions,
name: answerName,
type: suggestions.length ? 'suggest' : 'input',
},
]);
return answers[answerName];
} | javascript | async function requestInput(message, suggestions = []) {
const answerName = 'requestInput';
const answers = await inquirer.prompt([
{
message,
suggestions,
name: answerName,
type: suggestions.length ? 'suggest' : 'input',
},
]);
return answers[answerName];
} | [
"async",
"function",
"requestInput",
"(",
"message",
",",
"suggestions",
"=",
"[",
"]",
")",
"{",
"const",
"answerName",
"=",
"'requestInput'",
";",
"const",
"answers",
"=",
"await",
"inquirer",
".",
"prompt",
"(",
"[",
"{",
"message",
",",
"suggestions",
",",
"name",
":",
"answerName",
",",
"type",
":",
"suggestions",
".",
"length",
"?",
"'suggest'",
":",
"'input'",
",",
"}",
",",
"]",
")",
";",
"return",
"answers",
"[",
"answerName",
"]",
";",
"}"
] | Requests input from the user.
@param {string} message The prompt message.
@param {string[]} suggestions The input suggestions. | [
"Requests",
"input",
"from",
"the",
"user",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/requestInput.js#L11-L22 |
8,579 | olistic/warriorjs | packages/warriorjs-core/src/getLevel.js | getLevel | function getLevel(levelConfig) {
const level = loadLevel(levelConfig);
return JSON.parse(JSON.stringify(level));
} | javascript | function getLevel(levelConfig) {
const level = loadLevel(levelConfig);
return JSON.parse(JSON.stringify(level));
} | [
"function",
"getLevel",
"(",
"levelConfig",
")",
"{",
"const",
"level",
"=",
"loadLevel",
"(",
"levelConfig",
")",
";",
"return",
"JSON",
".",
"parse",
"(",
"JSON",
".",
"stringify",
"(",
"level",
")",
")",
";",
"}"
] | Returns the level for the given level config.
@param {Object} levelConfig The config of the level.
@returns {Object} The level. | [
"Returns",
"the",
"level",
"for",
"the",
"given",
"level",
"config",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-core/src/getLevel.js#L10-L13 |
8,580 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printTotalScore.js | printTotalScore | function printTotalScore(currentScore, addition) {
if (currentScore === 0) {
printLine(`Total Score: ${addition.toString()}`);
} else {
printLine(
`Total Score: ${currentScore} + ${addition} = ${currentScore + addition}`,
);
}
} | javascript | function printTotalScore(currentScore, addition) {
if (currentScore === 0) {
printLine(`Total Score: ${addition.toString()}`);
} else {
printLine(
`Total Score: ${currentScore} + ${addition} = ${currentScore + addition}`,
);
}
} | [
"function",
"printTotalScore",
"(",
"currentScore",
",",
"addition",
")",
"{",
"if",
"(",
"currentScore",
"===",
"0",
")",
"{",
"printLine",
"(",
"`",
"${",
"addition",
".",
"toString",
"(",
")",
"}",
"`",
")",
";",
"}",
"else",
"{",
"printLine",
"(",
"`",
"${",
"currentScore",
"}",
"${",
"addition",
"}",
"${",
"currentScore",
"+",
"addition",
"}",
"`",
",",
")",
";",
"}",
"}"
] | Prints the total score as the sum of the current score and the addition.
If the current score is zero, just the addition and not the sum will be
printed.
@param {number} currentScore The current score.
@param {number} addition The score to add to the current score. | [
"Prints",
"the",
"total",
"score",
"as",
"the",
"sum",
"of",
"the",
"current",
"score",
"and",
"the",
"addition",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printTotalScore.js#L12-L20 |
8,581 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printPlay.js | printPlay | async function printPlay(events, delay) {
let turnNumber = 0;
let boardOffset = 0;
await sleep(delay);
// eslint-disable-next-line no-restricted-syntax
for (const turnEvents of events) {
turnNumber += 1;
boardOffset = 0;
printTurnHeader(turnNumber);
// eslint-disable-next-line no-restricted-syntax
for (const event of turnEvents) {
printBoard(event.floorMap, event.warriorStatus, boardOffset);
printLogMessage(event.unit, event.message);
boardOffset += 1;
await sleep(delay); // eslint-disable-line no-await-in-loop
}
}
} | javascript | async function printPlay(events, delay) {
let turnNumber = 0;
let boardOffset = 0;
await sleep(delay);
// eslint-disable-next-line no-restricted-syntax
for (const turnEvents of events) {
turnNumber += 1;
boardOffset = 0;
printTurnHeader(turnNumber);
// eslint-disable-next-line no-restricted-syntax
for (const event of turnEvents) {
printBoard(event.floorMap, event.warriorStatus, boardOffset);
printLogMessage(event.unit, event.message);
boardOffset += 1;
await sleep(delay); // eslint-disable-line no-await-in-loop
}
}
} | [
"async",
"function",
"printPlay",
"(",
"events",
",",
"delay",
")",
"{",
"let",
"turnNumber",
"=",
"0",
";",
"let",
"boardOffset",
"=",
"0",
";",
"await",
"sleep",
"(",
"delay",
")",
";",
"// eslint-disable-next-line no-restricted-syntax",
"for",
"(",
"const",
"turnEvents",
"of",
"events",
")",
"{",
"turnNumber",
"+=",
"1",
";",
"boardOffset",
"=",
"0",
";",
"printTurnHeader",
"(",
"turnNumber",
")",
";",
"// eslint-disable-next-line no-restricted-syntax",
"for",
"(",
"const",
"event",
"of",
"turnEvents",
")",
"{",
"printBoard",
"(",
"event",
".",
"floorMap",
",",
"event",
".",
"warriorStatus",
",",
"boardOffset",
")",
";",
"printLogMessage",
"(",
"event",
".",
"unit",
",",
"event",
".",
"message",
")",
";",
"boardOffset",
"+=",
"1",
";",
"await",
"sleep",
"(",
"delay",
")",
";",
"// eslint-disable-line no-await-in-loop",
"}",
"}",
"}"
] | Prints a play.
@param {Object[]} events The events that happened during the play.
@param {nunber} delay The delay between each turn in ms. | [
"Prints",
"a",
"play",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printPlay.js#L13-L34 |
8,582 | olistic/warriorjs | packages/warriorjs-helper-get-level-score/src/isFloorClear.js | isFloorClear | function isFloorClear(floorMap) {
const spaces = floorMap.reduce((acc, val) => acc.concat(val), []);
const unitCount = spaces.filter(space => !!space.unit).length;
return unitCount <= 1;
} | javascript | function isFloorClear(floorMap) {
const spaces = floorMap.reduce((acc, val) => acc.concat(val), []);
const unitCount = spaces.filter(space => !!space.unit).length;
return unitCount <= 1;
} | [
"function",
"isFloorClear",
"(",
"floorMap",
")",
"{",
"const",
"spaces",
"=",
"floorMap",
".",
"reduce",
"(",
"(",
"acc",
",",
"val",
")",
"=>",
"acc",
".",
"concat",
"(",
"val",
")",
",",
"[",
"]",
")",
";",
"const",
"unitCount",
"=",
"spaces",
".",
"filter",
"(",
"space",
"=>",
"!",
"!",
"space",
".",
"unit",
")",
".",
"length",
";",
"return",
"unitCount",
"<=",
"1",
";",
"}"
] | Checks if the floor is clear.
The floor is clear when there are no units other than the warrior.
@returns {boolean} Whether the floor is clear or not. | [
"Checks",
"if",
"the",
"floor",
"is",
"clear",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-helper-get-level-score/src/isFloorClear.js#L8-L12 |
8,583 | olistic/warriorjs | packages/warriorjs-cli/src/ui/printLevelHeader.js | printLevelHeader | function printLevelHeader(levelNumber) {
printRow(chalk.gray.dim(` level ${levelNumber} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | javascript | function printLevelHeader(levelNumber) {
printRow(chalk.gray.dim(` level ${levelNumber} `), {
position: 'middle',
padding: chalk.gray.dim('~'),
});
} | [
"function",
"printLevelHeader",
"(",
"levelNumber",
")",
"{",
"printRow",
"(",
"chalk",
".",
"gray",
".",
"dim",
"(",
"`",
"${",
"levelNumber",
"}",
"`",
")",
",",
"{",
"position",
":",
"'middle'",
",",
"padding",
":",
"chalk",
".",
"gray",
".",
"dim",
"(",
"'~'",
")",
",",
"}",
")",
";",
"}"
] | Prints the level header.
@param {number} levelNumber The level number. | [
"Prints",
"the",
"level",
"header",
"."
] | ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8 | https://github.com/olistic/warriorjs/blob/ec531b4d4b6b7c3e51e5adbd03f575af56ebebc8/packages/warriorjs-cli/src/ui/printLevelHeader.js#L10-L15 |
8,584 | jsforce/jsforce | lib/query.js | function(err, res) {
if (_.isFunction(callback)) {
try {
res = callback(err, res);
err = null;
} catch(e) {
err = e;
}
}
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res);
}
} | javascript | function(err, res) {
if (_.isFunction(callback)) {
try {
res = callback(err, res);
err = null;
} catch(e) {
err = e;
}
}
if (err) {
deferred.reject(err);
} else {
deferred.resolve(res);
}
} | [
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"try",
"{",
"res",
"=",
"callback",
"(",
"err",
",",
"res",
")",
";",
"err",
"=",
"null",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"err",
"=",
"e",
";",
"}",
"}",
"if",
"(",
"err",
")",
"{",
"deferred",
".",
"reject",
"(",
"err",
")",
";",
"}",
"else",
"{",
"deferred",
".",
"resolve",
"(",
"res",
")",
";",
"}",
"}"
] | callback and promise resolution; | [
"callback",
"and",
"promise",
"resolution",
";"
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/query.js#L334-L348 |
|
8,585 | jsforce/jsforce | lib/oauth2.js | function(params) {
params = _.extend({
response_type : "code",
client_id : this.clientId,
redirect_uri : this.redirectUri
}, params || {});
return this.authzServiceUrl +
(this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
querystring.stringify(params);
} | javascript | function(params) {
params = _.extend({
response_type : "code",
client_id : this.clientId,
redirect_uri : this.redirectUri
}, params || {});
return this.authzServiceUrl +
(this.authzServiceUrl.indexOf('?') >= 0 ? "&" : "?") +
querystring.stringify(params);
} | [
"function",
"(",
"params",
")",
"{",
"params",
"=",
"_",
".",
"extend",
"(",
"{",
"response_type",
":",
"\"code\"",
",",
"client_id",
":",
"this",
".",
"clientId",
",",
"redirect_uri",
":",
"this",
".",
"redirectUri",
"}",
",",
"params",
"||",
"{",
"}",
")",
";",
"return",
"this",
".",
"authzServiceUrl",
"+",
"(",
"this",
".",
"authzServiceUrl",
".",
"indexOf",
"(",
"'?'",
")",
">=",
"0",
"?",
"\"&\"",
":",
"\"?\"",
")",
"+",
"querystring",
".",
"stringify",
"(",
"params",
")",
";",
"}"
] | Get Salesforce OAuth2 authorization page URL to redirect user agent.
@param {Object} params - Parameters
@param {String} [params.scope] - Scope values in space-separated string
@param {String} [params.state] - State parameter
@param {String} [params.code_challenge] - Code challenge value (RFC 7636 - Proof Key of Code Exchange)
@returns {String} Authorization page URL | [
"Get",
"Salesforce",
"OAuth2",
"authorization",
"page",
"URL",
"to",
"redirect",
"user",
"agent",
"."
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/oauth2.js#L69-L78 |
|
8,586 | jsforce/jsforce | lib/oauth2.js | function(token, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.revokeServiceUrl,
body: querystring.stringify({ token: token }),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
if (response.statusCode >= 400) {
var res = querystring.parse(response.body);
if (!res || !res.error) {
res = { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
}
var err = new Error(res.error_description);
err.name = res.error;
throw err;
}
}).thenCall(callback);
} | javascript | function(token, callback) {
return this._transport.httpRequest({
method : 'POST',
url : this.revokeServiceUrl,
body: querystring.stringify({ token: token }),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
}
}).then(function(response) {
if (response.statusCode >= 400) {
var res = querystring.parse(response.body);
if (!res || !res.error) {
res = { error: "ERROR_HTTP_"+response.statusCode, error_description: response.body };
}
var err = new Error(res.error_description);
err.name = res.error;
throw err;
}
}).thenCall(callback);
} | [
"function",
"(",
"token",
",",
"callback",
")",
"{",
"return",
"this",
".",
"_transport",
".",
"httpRequest",
"(",
"{",
"method",
":",
"'POST'",
",",
"url",
":",
"this",
".",
"revokeServiceUrl",
",",
"body",
":",
"querystring",
".",
"stringify",
"(",
"{",
"token",
":",
"token",
"}",
")",
",",
"headers",
":",
"{",
"\"Content-Type\"",
":",
"\"application/x-www-form-urlencoded\"",
"}",
"}",
")",
".",
"then",
"(",
"function",
"(",
"response",
")",
"{",
"if",
"(",
"response",
".",
"statusCode",
">=",
"400",
")",
"{",
"var",
"res",
"=",
"querystring",
".",
"parse",
"(",
"response",
".",
"body",
")",
";",
"if",
"(",
"!",
"res",
"||",
"!",
"res",
".",
"error",
")",
"{",
"res",
"=",
"{",
"error",
":",
"\"ERROR_HTTP_\"",
"+",
"response",
".",
"statusCode",
",",
"error_description",
":",
"response",
".",
"body",
"}",
";",
"}",
"var",
"err",
"=",
"new",
"Error",
"(",
"res",
".",
"error_description",
")",
";",
"err",
".",
"name",
"=",
"res",
".",
"error",
";",
"throw",
"err",
";",
"}",
"}",
")",
".",
"thenCall",
"(",
"callback",
")",
";",
"}"
] | OAuth2 Revoke Session or API Token
@param {String} token - Access or Refresh token to revoke. Passing in the Access token revokes the session. Passing in the Refresh token revokes API Access.
@param {Callback.<undefined>} [callback] - Callback function
@returns {Promise.<undefined>} | [
"OAuth2",
"Revoke",
"Session",
"or",
"API",
"Token"
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/oauth2.js#L159-L178 |
|
8,587 | jsforce/jsforce | lib/cache.js | createCacheKey | function createCacheKey(namespace, args) {
args = Array.prototype.slice.apply(args);
return namespace + '(' + _.map(args, function(a){ return JSON.stringify(a); }).join(',') + ')';
} | javascript | function createCacheKey(namespace, args) {
args = Array.prototype.slice.apply(args);
return namespace + '(' + _.map(args, function(a){ return JSON.stringify(a); }).join(',') + ')';
} | [
"function",
"createCacheKey",
"(",
"namespace",
",",
"args",
")",
"{",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"apply",
"(",
"args",
")",
";",
"return",
"namespace",
"+",
"'('",
"+",
"_",
".",
"map",
"(",
"args",
",",
"function",
"(",
"a",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"a",
")",
";",
"}",
")",
".",
"join",
"(",
"','",
")",
"+",
"')'",
";",
"}"
] | create and return cache key from namespace and serialized arguments.
@private | [
"create",
"and",
"return",
"cache",
"key",
"from",
"namespace",
"and",
"serialized",
"arguments",
"."
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/cache.js#L104-L107 |
8,588 | jsforce/jsforce | lib/http-api.js | function(conn, options) {
options = options || {};
this._conn = conn;
this.on('resume', function(err) { conn.emit('resume', err); });
this._responseType = options.responseType;
this._transport = options.transport || conn._transport;
this._noContentResponse = options.noContentResponse;
} | javascript | function(conn, options) {
options = options || {};
this._conn = conn;
this.on('resume', function(err) { conn.emit('resume', err); });
this._responseType = options.responseType;
this._transport = options.transport || conn._transport;
this._noContentResponse = options.noContentResponse;
} | [
"function",
"(",
"conn",
",",
"options",
")",
"{",
"options",
"=",
"options",
"||",
"{",
"}",
";",
"this",
".",
"_conn",
"=",
"conn",
";",
"this",
".",
"on",
"(",
"'resume'",
",",
"function",
"(",
"err",
")",
"{",
"conn",
".",
"emit",
"(",
"'resume'",
",",
"err",
")",
";",
"}",
")",
";",
"this",
".",
"_responseType",
"=",
"options",
".",
"responseType",
";",
"this",
".",
"_transport",
"=",
"options",
".",
"transport",
"||",
"conn",
".",
"_transport",
";",
"this",
".",
"_noContentResponse",
"=",
"options",
".",
"noContentResponse",
";",
"}"
] | HTTP based API class with authorization hook
@constructor
@extends events.EventEmitter
@param {Connection} conn - Connection object
@param {Object} [options] - Http API Options
@param {String} [options.responseType] - Overriding content mime-type in response
@param {Transport} [options.transport] - Transport for http api
@param {Object} [options.noContentResponse] - Alternative response when no content returned in response (= HTTP 204) | [
"HTTP",
"based",
"API",
"class",
"with",
"authorization",
"hook"
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/http-api.js#L19-L26 |
|
8,589 | jsforce/jsforce | lib/cli/repl.js | injectBefore | function injectBefore(replServer, method, beforeFn) {
var _orig = replServer[method];
replServer[method] = function() {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
beforeFn.apply(null, args.concat(function(err, res) {
if (err || res) {
callback(err, res);
} else {
_orig.apply(replServer, args.concat(callback));
}
}));
};
return replServer;
} | javascript | function injectBefore(replServer, method, beforeFn) {
var _orig = replServer[method];
replServer[method] = function() {
var args = Array.prototype.slice.call(arguments);
var callback = args.pop();
beforeFn.apply(null, args.concat(function(err, res) {
if (err || res) {
callback(err, res);
} else {
_orig.apply(replServer, args.concat(callback));
}
}));
};
return replServer;
} | [
"function",
"injectBefore",
"(",
"replServer",
",",
"method",
",",
"beforeFn",
")",
"{",
"var",
"_orig",
"=",
"replServer",
"[",
"method",
"]",
";",
"replServer",
"[",
"method",
"]",
"=",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"Array",
".",
"prototype",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"var",
"callback",
"=",
"args",
".",
"pop",
"(",
")",
";",
"beforeFn",
".",
"apply",
"(",
"null",
",",
"args",
".",
"concat",
"(",
"function",
"(",
"err",
",",
"res",
")",
"{",
"if",
"(",
"err",
"||",
"res",
")",
"{",
"callback",
"(",
"err",
",",
"res",
")",
";",
"}",
"else",
"{",
"_orig",
".",
"apply",
"(",
"replServer",
",",
"args",
".",
"concat",
"(",
"callback",
")",
")",
";",
"}",
"}",
")",
")",
";",
"}",
";",
"return",
"replServer",
";",
"}"
] | Intercept the evaled value returned from repl evaluator, convert and send back to output.
@private | [
"Intercept",
"the",
"evaled",
"value",
"returned",
"from",
"repl",
"evaluator",
"convert",
"and",
"send",
"back",
"to",
"output",
"."
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/cli/repl.js#L21-L35 |
8,590 | jsforce/jsforce | lib/cli/repl.js | promisify | function promisify(err, value, callback) {
if (err) { throw err; }
if (isPromiseLike(value)) {
value.then(function(v) {
callback(null, v);
}, function(err) {
callback(err);
});
} else {
callback(null, value);
}
} | javascript | function promisify(err, value, callback) {
if (err) { throw err; }
if (isPromiseLike(value)) {
value.then(function(v) {
callback(null, v);
}, function(err) {
callback(err);
});
} else {
callback(null, value);
}
} | [
"function",
"promisify",
"(",
"err",
",",
"value",
",",
"callback",
")",
"{",
"if",
"(",
"err",
")",
"{",
"throw",
"err",
";",
"}",
"if",
"(",
"isPromiseLike",
"(",
"value",
")",
")",
"{",
"value",
".",
"then",
"(",
"function",
"(",
"v",
")",
"{",
"callback",
"(",
"null",
",",
"v",
")",
";",
"}",
",",
"function",
"(",
"err",
")",
"{",
"callback",
"(",
"err",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"callback",
"(",
"null",
",",
"value",
")",
";",
"}",
"}"
] | When the result was "promise", resolve its value
@private | [
"When",
"the",
"result",
"was",
"promise",
"resolve",
"its",
"value"
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/cli/repl.js#L62-L73 |
8,591 | jsforce/jsforce | lib/cli/repl.js | outputToStdout | function outputToStdout(prettyPrint) {
if (prettyPrint && !_.isNumber(prettyPrint)) {
prettyPrint = 4;
}
return function(err, value, callback) {
if (err) {
console.error(err);
} else {
var str = JSON.stringify(value, null, prettyPrint);
console.log(str);
}
callback(err, value);
};
} | javascript | function outputToStdout(prettyPrint) {
if (prettyPrint && !_.isNumber(prettyPrint)) {
prettyPrint = 4;
}
return function(err, value, callback) {
if (err) {
console.error(err);
} else {
var str = JSON.stringify(value, null, prettyPrint);
console.log(str);
}
callback(err, value);
};
} | [
"function",
"outputToStdout",
"(",
"prettyPrint",
")",
"{",
"if",
"(",
"prettyPrint",
"&&",
"!",
"_",
".",
"isNumber",
"(",
"prettyPrint",
")",
")",
"{",
"prettyPrint",
"=",
"4",
";",
"}",
"return",
"function",
"(",
"err",
",",
"value",
",",
"callback",
")",
"{",
"if",
"(",
"err",
")",
"{",
"console",
".",
"error",
"(",
"err",
")",
";",
"}",
"else",
"{",
"var",
"str",
"=",
"JSON",
".",
"stringify",
"(",
"value",
",",
"null",
",",
"prettyPrint",
")",
";",
"console",
".",
"log",
"(",
"str",
")",
";",
"}",
"callback",
"(",
"err",
",",
"value",
")",
";",
"}",
";",
"}"
] | Output object to stdout in JSON representation
@private | [
"Output",
"object",
"to",
"stdout",
"in",
"JSON",
"representation"
] | 3f9e567dd063c0a912594198a187ececf642cfa7 | https://github.com/jsforce/jsforce/blob/3f9e567dd063c0a912594198a187ececf642cfa7/lib/cli/repl.js#L87-L100 |
8,592 | babel/minify | packages/babel-plugin-minify-simplify/src/index.js | function(path) {
const { node } = path;
if (node.declarations.length < 2) {
return;
}
const inits = [];
const empty = [];
for (const decl of node.declarations) {
if (!decl.init) {
empty.push(decl);
} else {
inits.push(decl);
}
}
// This is based on exprimintation but there is a significant
// imrpovement when we place empty vars at the top in smaller
// files. Whereas it hurts in larger files.
if (this.fitsInSlidingWindow) {
node.declarations = empty.concat(inits);
} else {
node.declarations = inits.concat(empty);
}
} | javascript | function(path) {
const { node } = path;
if (node.declarations.length < 2) {
return;
}
const inits = [];
const empty = [];
for (const decl of node.declarations) {
if (!decl.init) {
empty.push(decl);
} else {
inits.push(decl);
}
}
// This is based on exprimintation but there is a significant
// imrpovement when we place empty vars at the top in smaller
// files. Whereas it hurts in larger files.
if (this.fitsInSlidingWindow) {
node.declarations = empty.concat(inits);
} else {
node.declarations = inits.concat(empty);
}
} | [
"function",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"node",
".",
"declarations",
".",
"length",
"<",
"2",
")",
"{",
"return",
";",
"}",
"const",
"inits",
"=",
"[",
"]",
";",
"const",
"empty",
"=",
"[",
"]",
";",
"for",
"(",
"const",
"decl",
"of",
"node",
".",
"declarations",
")",
"{",
"if",
"(",
"!",
"decl",
".",
"init",
")",
"{",
"empty",
".",
"push",
"(",
"decl",
")",
";",
"}",
"else",
"{",
"inits",
".",
"push",
"(",
"decl",
")",
";",
"}",
"}",
"// This is based on exprimintation but there is a significant",
"// imrpovement when we place empty vars at the top in smaller",
"// files. Whereas it hurts in larger files.",
"if",
"(",
"this",
".",
"fitsInSlidingWindow",
")",
"{",
"node",
".",
"declarations",
"=",
"empty",
".",
"concat",
"(",
"inits",
")",
";",
"}",
"else",
"{",
"node",
".",
"declarations",
"=",
"inits",
".",
"concat",
"(",
"empty",
")",
";",
"}",
"}"
] | Put vars with no init at the top. | [
"Put",
"vars",
"with",
"no",
"init",
"at",
"the",
"top",
"."
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/index.js#L278-L303 |
|
8,593 | babel/minify | packages/babel-plugin-minify-simplify/src/index.js | function(path) {
const { node } = path;
if (
!path.parentPath.parentPath.isFunction() ||
path.getSibling(path.key + 1).node
) {
return;
}
if (!node.argument) {
path.remove();
return;
}
if (t.isUnaryExpression(node.argument, { operator: "void" })) {
path.replaceWith(node.argument.argument);
}
} | javascript | function(path) {
const { node } = path;
if (
!path.parentPath.parentPath.isFunction() ||
path.getSibling(path.key + 1).node
) {
return;
}
if (!node.argument) {
path.remove();
return;
}
if (t.isUnaryExpression(node.argument, { operator: "void" })) {
path.replaceWith(node.argument.argument);
}
} | [
"function",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"!",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"isFunction",
"(",
")",
"||",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"+",
"1",
")",
".",
"node",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"node",
".",
"argument",
")",
"{",
"path",
".",
"remove",
"(",
")",
";",
"return",
";",
"}",
"if",
"(",
"t",
".",
"isUnaryExpression",
"(",
"node",
".",
"argument",
",",
"{",
"operator",
":",
"\"void\"",
"}",
")",
")",
"{",
"path",
".",
"replaceWith",
"(",
"node",
".",
"argument",
".",
"argument",
")",
";",
"}",
"}"
] | Remove return if last statement with no argument. Replace return with `void` argument with argument. | [
"Remove",
"return",
"if",
"last",
"statement",
"with",
"no",
"argument",
".",
"Replace",
"return",
"with",
"void",
"argument",
"with",
"argument",
"."
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/index.js#L592-L610 |
|
8,594 | babel/minify | packages/babel-plugin-minify-simplify/src/index.js | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const consTestPairs = [];
let fallThru = [];
let defaultRet;
for (const switchCase of node.cases) {
if (switchCase.consequent.length > 1) {
return;
}
const cons = switchCase.consequent[0];
// default case
if (!switchCase.test) {
if (!t.isReturnStatement(cons)) {
return;
}
defaultRet = cons;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
// TODO: can we void it?
if (!t.isReturnStatement(cons)) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultRet) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
consTestPairs.push([test, cons.argument || VOID_0]);
}
// Bail if we have any remaining fallthrough
if (fallThru.length) {
return;
}
// We need the default to be there to make sure there is an oppurtinity
// not to return.
if (!defaultRet) {
if (path.inList) {
const nextPath = path.getSibling(path.key + 1);
if (nextPath.isReturnStatement()) {
defaultRet = nextPath.node;
nextPath.remove();
} else if (
!nextPath.node &&
path.parentPath.parentPath.isFunction()
) {
// If this is the last statement in a function we just fake a void return.
defaultRet = t.returnStatement(VOID_0);
} else {
return;
}
} else {
return;
}
}
const cond = consTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultRet.argument || VOID_0
);
path.replaceWith(t.returnStatement(cond));
// Maybe now we can merge with some previous switch statement.
if (path.inList) {
const prev = path.getSibling(path.key - 1);
if (prev.isSwitchStatement()) {
prev.visit();
}
}
} | javascript | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const consTestPairs = [];
let fallThru = [];
let defaultRet;
for (const switchCase of node.cases) {
if (switchCase.consequent.length > 1) {
return;
}
const cons = switchCase.consequent[0];
// default case
if (!switchCase.test) {
if (!t.isReturnStatement(cons)) {
return;
}
defaultRet = cons;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
// TODO: can we void it?
if (!t.isReturnStatement(cons)) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultRet) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
consTestPairs.push([test, cons.argument || VOID_0]);
}
// Bail if we have any remaining fallthrough
if (fallThru.length) {
return;
}
// We need the default to be there to make sure there is an oppurtinity
// not to return.
if (!defaultRet) {
if (path.inList) {
const nextPath = path.getSibling(path.key + 1);
if (nextPath.isReturnStatement()) {
defaultRet = nextPath.node;
nextPath.remove();
} else if (
!nextPath.node &&
path.parentPath.parentPath.isFunction()
) {
// If this is the last statement in a function we just fake a void return.
defaultRet = t.returnStatement(VOID_0);
} else {
return;
}
} else {
return;
}
}
const cond = consTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultRet.argument || VOID_0
);
path.replaceWith(t.returnStatement(cond));
// Maybe now we can merge with some previous switch statement.
if (path.inList) {
const prev = path.getSibling(path.key - 1);
if (prev.isSwitchStatement()) {
prev.visit();
}
}
} | [
"function",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"// Need to be careful of side-effects.",
"if",
"(",
"!",
"t",
".",
"isIdentifier",
"(",
"node",
".",
"discriminant",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"node",
".",
"cases",
".",
"length",
")",
"{",
"return",
";",
"}",
"const",
"consTestPairs",
"=",
"[",
"]",
";",
"let",
"fallThru",
"=",
"[",
"]",
";",
"let",
"defaultRet",
";",
"for",
"(",
"const",
"switchCase",
"of",
"node",
".",
"cases",
")",
"{",
"if",
"(",
"switchCase",
".",
"consequent",
".",
"length",
">",
"1",
")",
"{",
"return",
";",
"}",
"const",
"cons",
"=",
"switchCase",
".",
"consequent",
"[",
"0",
"]",
";",
"// default case",
"if",
"(",
"!",
"switchCase",
".",
"test",
")",
"{",
"if",
"(",
"!",
"t",
".",
"isReturnStatement",
"(",
"cons",
")",
")",
"{",
"return",
";",
"}",
"defaultRet",
"=",
"cons",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"switchCase",
".",
"consequent",
".",
"length",
")",
"{",
"fallThru",
".",
"push",
"(",
"switchCase",
".",
"test",
")",
";",
"continue",
";",
"}",
"// TODO: can we void it?",
"if",
"(",
"!",
"t",
".",
"isReturnStatement",
"(",
"cons",
")",
")",
"{",
"return",
";",
"}",
"let",
"test",
"=",
"t",
".",
"binaryExpression",
"(",
"\"===\"",
",",
"node",
".",
"discriminant",
",",
"switchCase",
".",
"test",
")",
";",
"if",
"(",
"fallThru",
".",
"length",
"&&",
"!",
"defaultRet",
")",
"{",
"test",
"=",
"fallThru",
".",
"reduceRight",
"(",
"(",
"right",
",",
"test",
")",
"=>",
"t",
".",
"logicalExpression",
"(",
"\"||\"",
",",
"t",
".",
"binaryExpression",
"(",
"\"===\"",
",",
"node",
".",
"discriminant",
",",
"test",
")",
",",
"right",
")",
",",
"test",
")",
";",
"}",
"fallThru",
"=",
"[",
"]",
";",
"consTestPairs",
".",
"push",
"(",
"[",
"test",
",",
"cons",
".",
"argument",
"||",
"VOID_0",
"]",
")",
";",
"}",
"// Bail if we have any remaining fallthrough",
"if",
"(",
"fallThru",
".",
"length",
")",
"{",
"return",
";",
"}",
"// We need the default to be there to make sure there is an oppurtinity",
"// not to return.",
"if",
"(",
"!",
"defaultRet",
")",
"{",
"if",
"(",
"path",
".",
"inList",
")",
"{",
"const",
"nextPath",
"=",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"+",
"1",
")",
";",
"if",
"(",
"nextPath",
".",
"isReturnStatement",
"(",
")",
")",
"{",
"defaultRet",
"=",
"nextPath",
".",
"node",
";",
"nextPath",
".",
"remove",
"(",
")",
";",
"}",
"else",
"if",
"(",
"!",
"nextPath",
".",
"node",
"&&",
"path",
".",
"parentPath",
".",
"parentPath",
".",
"isFunction",
"(",
")",
")",
"{",
"// If this is the last statement in a function we just fake a void return.",
"defaultRet",
"=",
"t",
".",
"returnStatement",
"(",
"VOID_0",
")",
";",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"else",
"{",
"return",
";",
"}",
"}",
"const",
"cond",
"=",
"consTestPairs",
".",
"reduceRight",
"(",
"(",
"alt",
",",
"[",
"test",
",",
"cons",
"]",
")",
"=>",
"t",
".",
"conditionalExpression",
"(",
"test",
",",
"cons",
",",
"alt",
")",
",",
"defaultRet",
".",
"argument",
"||",
"VOID_0",
")",
";",
"path",
".",
"replaceWith",
"(",
"t",
".",
"returnStatement",
"(",
"cond",
")",
")",
";",
"// Maybe now we can merge with some previous switch statement.",
"if",
"(",
"path",
".",
"inList",
")",
"{",
"const",
"prev",
"=",
"path",
".",
"getSibling",
"(",
"path",
".",
"key",
"-",
"1",
")",
";",
"if",
"(",
"prev",
".",
"isSwitchStatement",
"(",
")",
")",
"{",
"prev",
".",
"visit",
"(",
")",
";",
"}",
"}",
"}"
] | Convert switch statements with all returns in their cases to return conditional. | [
"Convert",
"switch",
"statements",
"with",
"all",
"returns",
"in",
"their",
"cases",
"to",
"return",
"conditional",
"."
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/index.js#L670-L774 |
|
8,595 | babel/minify | packages/babel-plugin-minify-simplify/src/index.js | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const exprTestPairs = [];
let fallThru = [];
let defaultExpr;
for (const switchCase of node.cases) {
if (!switchCase.test) {
if (switchCase.consequent.length !== 1) {
return;
}
if (!t.isExpressionStatement(switchCase.consequent[0])) {
return;
}
defaultExpr = switchCase.consequent[0].expression;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
const [cons, breakStatement] = switchCase.consequent;
if (switchCase === node.cases[node.cases.length - 1]) {
if (breakStatement && !t.isBreakStatement(breakStatement)) {
return;
}
} else if (!t.isBreakStatement(breakStatement)) {
return;
}
if (
!t.isExpressionStatement(cons) ||
switchCase.consequent.length > 2
) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultExpr) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
exprTestPairs.push([test, cons.expression]);
}
if (fallThru.length) {
return;
}
const cond = exprTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultExpr || VOID_0
);
path.replaceWith(cond);
} | javascript | function(path) {
const { node } = path;
// Need to be careful of side-effects.
if (!t.isIdentifier(node.discriminant)) {
return;
}
if (!node.cases.length) {
return;
}
const exprTestPairs = [];
let fallThru = [];
let defaultExpr;
for (const switchCase of node.cases) {
if (!switchCase.test) {
if (switchCase.consequent.length !== 1) {
return;
}
if (!t.isExpressionStatement(switchCase.consequent[0])) {
return;
}
defaultExpr = switchCase.consequent[0].expression;
continue;
}
if (!switchCase.consequent.length) {
fallThru.push(switchCase.test);
continue;
}
const [cons, breakStatement] = switchCase.consequent;
if (switchCase === node.cases[node.cases.length - 1]) {
if (breakStatement && !t.isBreakStatement(breakStatement)) {
return;
}
} else if (!t.isBreakStatement(breakStatement)) {
return;
}
if (
!t.isExpressionStatement(cons) ||
switchCase.consequent.length > 2
) {
return;
}
let test = t.binaryExpression(
"===",
node.discriminant,
switchCase.test
);
if (fallThru.length && !defaultExpr) {
test = fallThru.reduceRight(
(right, test) =>
t.logicalExpression(
"||",
t.binaryExpression("===", node.discriminant, test),
right
),
test
);
}
fallThru = [];
exprTestPairs.push([test, cons.expression]);
}
if (fallThru.length) {
return;
}
const cond = exprTestPairs.reduceRight(
(alt, [test, cons]) => t.conditionalExpression(test, cons, alt),
defaultExpr || VOID_0
);
path.replaceWith(cond);
} | [
"function",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"// Need to be careful of side-effects.",
"if",
"(",
"!",
"t",
".",
"isIdentifier",
"(",
"node",
".",
"discriminant",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"node",
".",
"cases",
".",
"length",
")",
"{",
"return",
";",
"}",
"const",
"exprTestPairs",
"=",
"[",
"]",
";",
"let",
"fallThru",
"=",
"[",
"]",
";",
"let",
"defaultExpr",
";",
"for",
"(",
"const",
"switchCase",
"of",
"node",
".",
"cases",
")",
"{",
"if",
"(",
"!",
"switchCase",
".",
"test",
")",
"{",
"if",
"(",
"switchCase",
".",
"consequent",
".",
"length",
"!==",
"1",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"t",
".",
"isExpressionStatement",
"(",
"switchCase",
".",
"consequent",
"[",
"0",
"]",
")",
")",
"{",
"return",
";",
"}",
"defaultExpr",
"=",
"switchCase",
".",
"consequent",
"[",
"0",
"]",
".",
"expression",
";",
"continue",
";",
"}",
"if",
"(",
"!",
"switchCase",
".",
"consequent",
".",
"length",
")",
"{",
"fallThru",
".",
"push",
"(",
"switchCase",
".",
"test",
")",
";",
"continue",
";",
"}",
"const",
"[",
"cons",
",",
"breakStatement",
"]",
"=",
"switchCase",
".",
"consequent",
";",
"if",
"(",
"switchCase",
"===",
"node",
".",
"cases",
"[",
"node",
".",
"cases",
".",
"length",
"-",
"1",
"]",
")",
"{",
"if",
"(",
"breakStatement",
"&&",
"!",
"t",
".",
"isBreakStatement",
"(",
"breakStatement",
")",
")",
"{",
"return",
";",
"}",
"}",
"else",
"if",
"(",
"!",
"t",
".",
"isBreakStatement",
"(",
"breakStatement",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"t",
".",
"isExpressionStatement",
"(",
"cons",
")",
"||",
"switchCase",
".",
"consequent",
".",
"length",
">",
"2",
")",
"{",
"return",
";",
"}",
"let",
"test",
"=",
"t",
".",
"binaryExpression",
"(",
"\"===\"",
",",
"node",
".",
"discriminant",
",",
"switchCase",
".",
"test",
")",
";",
"if",
"(",
"fallThru",
".",
"length",
"&&",
"!",
"defaultExpr",
")",
"{",
"test",
"=",
"fallThru",
".",
"reduceRight",
"(",
"(",
"right",
",",
"test",
")",
"=>",
"t",
".",
"logicalExpression",
"(",
"\"||\"",
",",
"t",
".",
"binaryExpression",
"(",
"\"===\"",
",",
"node",
".",
"discriminant",
",",
"test",
")",
",",
"right",
")",
",",
"test",
")",
";",
"}",
"fallThru",
"=",
"[",
"]",
";",
"exprTestPairs",
".",
"push",
"(",
"[",
"test",
",",
"cons",
".",
"expression",
"]",
")",
";",
"}",
"if",
"(",
"fallThru",
".",
"length",
")",
"{",
"return",
";",
"}",
"const",
"cond",
"=",
"exprTestPairs",
".",
"reduceRight",
"(",
"(",
"alt",
",",
"[",
"test",
",",
"cons",
"]",
")",
"=>",
"t",
".",
"conditionalExpression",
"(",
"test",
",",
"cons",
",",
"alt",
")",
",",
"defaultExpr",
"||",
"VOID_0",
")",
";",
"path",
".",
"replaceWith",
"(",
"cond",
")",
";",
"}"
] | Convert switches into conditionals. | [
"Convert",
"switches",
"into",
"conditionals",
"."
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/index.js#L777-L856 |
|
8,596 | babel/minify | packages/babel-plugin-minify-simplify/src/if-statement.js | toGuardedExpression | function toGuardedExpression(path) {
const { node } = path;
if (
node.consequent &&
!node.alternate &&
node.consequent.type === "ExpressionStatement"
) {
let op = "&&";
if (t.isUnaryExpression(node.test, { operator: "!" })) {
node.test = node.test.argument;
op = "||";
}
path.replaceWith(
t.expressionStatement(
t.logicalExpression(op, node.test, node.consequent.expression)
)
);
return REPLACED;
}
} | javascript | function toGuardedExpression(path) {
const { node } = path;
if (
node.consequent &&
!node.alternate &&
node.consequent.type === "ExpressionStatement"
) {
let op = "&&";
if (t.isUnaryExpression(node.test, { operator: "!" })) {
node.test = node.test.argument;
op = "||";
}
path.replaceWith(
t.expressionStatement(
t.logicalExpression(op, node.test, node.consequent.expression)
)
);
return REPLACED;
}
} | [
"function",
"toGuardedExpression",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"node",
".",
"consequent",
"&&",
"!",
"node",
".",
"alternate",
"&&",
"node",
".",
"consequent",
".",
"type",
"===",
"\"ExpressionStatement\"",
")",
"{",
"let",
"op",
"=",
"\"&&\"",
";",
"if",
"(",
"t",
".",
"isUnaryExpression",
"(",
"node",
".",
"test",
",",
"{",
"operator",
":",
"\"!\"",
"}",
")",
")",
"{",
"node",
".",
"test",
"=",
"node",
".",
"test",
".",
"argument",
";",
"op",
"=",
"\"||\"",
";",
"}",
"path",
".",
"replaceWith",
"(",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"logicalExpression",
"(",
"op",
",",
"node",
".",
"test",
",",
"node",
".",
"consequent",
".",
"expression",
")",
")",
")",
";",
"return",
"REPLACED",
";",
"}",
"}"
] | No alternate, make into a guarded expression | [
"No",
"alternate",
"make",
"into",
"a",
"guarded",
"expression"
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/if-statement.js#L24-L44 |
8,597 | babel/minify | packages/babel-plugin-minify-simplify/src/if-statement.js | toTernary | function toTernary(path) {
const { node } = path;
if (
t.isExpressionStatement(node.consequent) &&
t.isExpressionStatement(node.alternate)
) {
path.replaceWith(
t.conditionalExpression(
node.test,
node.consequent.expression,
node.alternate.expression
)
);
return REPLACED;
}
} | javascript | function toTernary(path) {
const { node } = path;
if (
t.isExpressionStatement(node.consequent) &&
t.isExpressionStatement(node.alternate)
) {
path.replaceWith(
t.conditionalExpression(
node.test,
node.consequent.expression,
node.alternate.expression
)
);
return REPLACED;
}
} | [
"function",
"toTernary",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"t",
".",
"isExpressionStatement",
"(",
"node",
".",
"consequent",
")",
"&&",
"t",
".",
"isExpressionStatement",
"(",
"node",
".",
"alternate",
")",
")",
"{",
"path",
".",
"replaceWith",
"(",
"t",
".",
"conditionalExpression",
"(",
"node",
".",
"test",
",",
"node",
".",
"consequent",
".",
"expression",
",",
"node",
".",
"alternate",
".",
"expression",
")",
")",
";",
"return",
"REPLACED",
";",
"}",
"}"
] | both consequent and alternate are expressions, turn into ternary | [
"both",
"consequent",
"and",
"alternate",
"are",
"expressions",
"turn",
"into",
"ternary"
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/if-statement.js#L47-L62 |
8,598 | babel/minify | packages/babel-plugin-minify-simplify/src/if-statement.js | removeUnnecessaryElse | function removeUnnecessaryElse(path) {
const { node } = path;
const consequent = path.get("consequent");
const alternate = path.get("alternate");
if (
consequent.node &&
alternate.node &&
(consequent.isReturnStatement() ||
(consequent.isBlockStatement() &&
t.isReturnStatement(
consequent.node.body[consequent.node.body.length - 1]
))) &&
// don't hoist declarations
// TODO: validate declarations after fixing scope issues
(alternate.isBlockStatement()
? !alternate
.get("body")
.some(
stmt =>
stmt.isVariableDeclaration({ kind: "let" }) ||
stmt.isVariableDeclaration({ kind: "const" })
)
: true)
) {
path.insertAfter(
alternate.isBlockStatement()
? alternate.node.body.map(el => t.clone(el))
: t.clone(alternate.node)
);
node.alternate = null;
return REPLACED;
}
} | javascript | function removeUnnecessaryElse(path) {
const { node } = path;
const consequent = path.get("consequent");
const alternate = path.get("alternate");
if (
consequent.node &&
alternate.node &&
(consequent.isReturnStatement() ||
(consequent.isBlockStatement() &&
t.isReturnStatement(
consequent.node.body[consequent.node.body.length - 1]
))) &&
// don't hoist declarations
// TODO: validate declarations after fixing scope issues
(alternate.isBlockStatement()
? !alternate
.get("body")
.some(
stmt =>
stmt.isVariableDeclaration({ kind: "let" }) ||
stmt.isVariableDeclaration({ kind: "const" })
)
: true)
) {
path.insertAfter(
alternate.isBlockStatement()
? alternate.node.body.map(el => t.clone(el))
: t.clone(alternate.node)
);
node.alternate = null;
return REPLACED;
}
} | [
"function",
"removeUnnecessaryElse",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"const",
"consequent",
"=",
"path",
".",
"get",
"(",
"\"consequent\"",
")",
";",
"const",
"alternate",
"=",
"path",
".",
"get",
"(",
"\"alternate\"",
")",
";",
"if",
"(",
"consequent",
".",
"node",
"&&",
"alternate",
".",
"node",
"&&",
"(",
"consequent",
".",
"isReturnStatement",
"(",
")",
"||",
"(",
"consequent",
".",
"isBlockStatement",
"(",
")",
"&&",
"t",
".",
"isReturnStatement",
"(",
"consequent",
".",
"node",
".",
"body",
"[",
"consequent",
".",
"node",
".",
"body",
".",
"length",
"-",
"1",
"]",
")",
")",
")",
"&&",
"// don't hoist declarations",
"// TODO: validate declarations after fixing scope issues",
"(",
"alternate",
".",
"isBlockStatement",
"(",
")",
"?",
"!",
"alternate",
".",
"get",
"(",
"\"body\"",
")",
".",
"some",
"(",
"stmt",
"=>",
"stmt",
".",
"isVariableDeclaration",
"(",
"{",
"kind",
":",
"\"let\"",
"}",
")",
"||",
"stmt",
".",
"isVariableDeclaration",
"(",
"{",
"kind",
":",
"\"const\"",
"}",
")",
")",
":",
"true",
")",
")",
"{",
"path",
".",
"insertAfter",
"(",
"alternate",
".",
"isBlockStatement",
"(",
")",
"?",
"alternate",
".",
"node",
".",
"body",
".",
"map",
"(",
"el",
"=>",
"t",
".",
"clone",
"(",
"el",
")",
")",
":",
"t",
".",
"clone",
"(",
"alternate",
".",
"node",
")",
")",
";",
"node",
".",
"alternate",
"=",
"null",
";",
"return",
"REPLACED",
";",
"}",
"}"
] | Remove else for if-return | [
"Remove",
"else",
"for",
"if",
"-",
"return"
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/if-statement.js#L267-L300 |
8,599 | babel/minify | packages/babel-plugin-minify-simplify/src/if-statement.js | switchConsequent | function switchConsequent(path) {
const { node } = path;
if (!node.alternate) {
return;
}
if (!t.isIfStatement(node.consequent)) {
return;
}
if (t.isIfStatement(node.alternate)) {
return;
}
node.test = t.unaryExpression("!", node.test, true);
[node.alternate, node.consequent] = [node.consequent, node.alternate];
} | javascript | function switchConsequent(path) {
const { node } = path;
if (!node.alternate) {
return;
}
if (!t.isIfStatement(node.consequent)) {
return;
}
if (t.isIfStatement(node.alternate)) {
return;
}
node.test = t.unaryExpression("!", node.test, true);
[node.alternate, node.consequent] = [node.consequent, node.alternate];
} | [
"function",
"switchConsequent",
"(",
"path",
")",
"{",
"const",
"{",
"node",
"}",
"=",
"path",
";",
"if",
"(",
"!",
"node",
".",
"alternate",
")",
"{",
"return",
";",
"}",
"if",
"(",
"!",
"t",
".",
"isIfStatement",
"(",
"node",
".",
"consequent",
")",
")",
"{",
"return",
";",
"}",
"if",
"(",
"t",
".",
"isIfStatement",
"(",
"node",
".",
"alternate",
")",
")",
"{",
"return",
";",
"}",
"node",
".",
"test",
"=",
"t",
".",
"unaryExpression",
"(",
"\"!\"",
",",
"node",
".",
"test",
",",
"true",
")",
";",
"[",
"node",
".",
"alternate",
",",
"node",
".",
"consequent",
"]",
"=",
"[",
"node",
".",
"consequent",
",",
"node",
".",
"alternate",
"]",
";",
"}"
] | If the consequent is if and the altenrate is not then switch them out. That way we know we don't have to print a block.x | [
"If",
"the",
"consequent",
"is",
"if",
"and",
"the",
"altenrate",
"is",
"not",
"then",
"switch",
"them",
"out",
".",
"That",
"way",
"we",
"know",
"we",
"don",
"t",
"have",
"to",
"print",
"a",
"block",
".",
"x"
] | 6b8bab6bf5905ebc3a5a9130662a5fef34886de4 | https://github.com/babel/minify/blob/6b8bab6bf5905ebc3a5a9130662a5fef34886de4/packages/babel-plugin-minify-simplify/src/if-statement.js#L325-L342 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.