const sumTree = tree =>
(Array.isArray(tree) ? tree : []).reduce((acc, n) => (
acc[0] += 1,
acc[1] += n.value,
sumTree(n.children).forEach((m, i) => acc[i] += m),
acc
), [ 0, 0 ]);const sumTree = function(tree) {
const stack = [];
const result = [ 0, 0 ];
for (let [ i, arr ] = this(tree); ++i < arr.length || stack.length;) {
if (i === arr.length) {
[ i, arr ] = stack.pop();
} else {
result[0] += 1;
result[1] += arr[i].value;
stack.push([ i, arr ]);
[ i, arr ] = this(arr[i].children);
}
}
return result;
}.bind(x => [ -1, x instanceof Array ? x : [] ]);const [ num, sum ] = sumTree([ obj ]);
const average = sum / num;
<div class="color-label red" @click="color = '#FB253E', textColor = '#ffffff' , strokeColor = '#ffffff';"></div> <div class="color-label green" @click="color = '#19AD6A' ,textColor = '#ffffff' , strokeColor = '#ffffff';"></div> <div class="color-label orange" @click="color = '#FC6621' ,textColor = '#ffffff' , strokeColor = '#ffffff';"></div> <div class="color-label blue" @click="color = '#1386a3' ,textColor = '#ffffff' , strokeColor = '#ffffff';"></div> <div class="color-label yellow" @click="color = '#FFED00' ,textColor = '#111111' , strokeColor = '#111111';"></div> <div class="color-label lightgreen" @click="color = '#00ff00' ,textColor = '#111111' , strokeColor = '#111111';"></div> <div class="color-label white" @click="color = '#ffffff' ,textColor = '#111111' , strokeColor = '#111111';"></div>
<div
v-for="n in colors"
:class="[ 'color-label', n.name ]"
@click="onColorClick(n.values)"
></div>data: () => ({
colors: [
{ values: [ '#FB253E', '#FFF', '#FFF' ], name: 'red' },
{ values: [ '#19AD6A', '#FFF', '#FFF' ], name: 'green' },
{ values: [ '#FC6621', '#FFF', '#FFF' ], name: 'orange' },
{ values: [ '#1386A3', '#FFF', '#FFF' ], name: 'blue' },
{ values: [ '#FFED00', '#111', '#111' ], name: 'yellow' },
{ values: [ '#00FF00', '#111', '#111' ], name: 'lightgreen' },
{ values: [ '#FFFFFF', '#111', '#111' ], name: 'white' },
],
...
}),
methods: {
onColorClick([ color, textColor, strokeColor ]) {
Object.assign(this, { color, textColor, strokeColor });
},
...
},<tspan x="0" y="-10" text-anchor="middle" alignment-baseline="middle" font-family="'Swiss721BT-RomanCondensed'" :style="{ 'font-size': firstLineFontSize }">{{ firstLine }}</tspan> <tspan x="0" y="17" text-anchor="middle" alignment-baseline="middle" font-family="'Swiss721BT-RomanCondensed'" :style="{ 'font-size': secondLineFontSize }">{{ secondLine }}</tspan> <tspan x="-2" y="45" text-anchor="middle" alignment-baseline="middle" font-family="'Swiss721BT-RomanCondensed'" :style="{ 'font-size': thirdLineFontSize }">{{ thirdLine }}</tspan></text> ... <input type="text" placeholder="enter 1 text line" @input="changeFirstLine"> <input type="number" value='25' @input="changeFirstLineFontSize"><span> px </span> <input type="text" placeholder="enter 2 text line" @input="changeSecondLine"> <input type="number" value='18' @input="changeSecondLineFontSize"><span> px </span> <input type="text" placeholder="enter 2 text line" @input="changeThirdLine"> <input type="number" value='18' @input="changeThirdLineFontSize"><span> px </span>
data: { firstLine: 'Your', secondLine: 'custom', thirdLine: 'text', firstLineFontSize: '25', secondLineFontSize: '18', thirdLineFontSize: '18', ... }, methods: { changeFirstLine: function(event) { this.firstLine = event.target.value; }, changeSecondLine: function(event) { this.secondLine = event.target.value; }, changeThirdLine: function(event) { this.thirdLine = event.target.value; }, changeFirstLineFontSize: function(event) { this.firstLineFontSize = event.target.value; }, changeSecondLineFontSize: function(event) { this.secondLineFontSize = event.target.value; }, changeThirdLineFontSize: function(event) { this.thirdLineFontSize = event.target.value; }, ...
<tspan
v-for="n in lines"
v-text="n.text || n.placeholder"
:x="n.x"
:y="n.y"
:style="{ 'font-size': n.fontSize }"
text-anchor="middle"
alignment-baseline="middle"
font-family="'Swiss721BT-RomanCondensed'"
></tspan>
...
<template v-for="(n, i) in lines">
<input type="text" v-model="n.text" :placeholder="`enter ${i + 1} text line`">
<input type="number" v-model="n.fontSize"><span> px </span>
</template>data: () => ({
lines: [
{ x: 0, y: -10, fontSize: 25, placeholder: 'Your' },
{ x: 0, y: 17, fontSize: 18, placeholder: 'custom' },
{ x: -2, y: 45, fontSize: 18, placeholder: 'text' },
],
...
}),
xmlns="http://www.w3.org/2000/svg" и xmlns:xlink="http://www.w3.org/1999/xlink".
const tower = length =>
Array.from({ length }, (n, i) => Array(2)
.fill(' '.repeat(length - i - 1))
.join('*'.repeat(i * 2 + 1))
);const tower = length =>
Array.from({ length }, (n, i) => (
n = Array(length - i).join(' '),
n + Array(-~i << 1).join('*') + n
));
const FILTER_VALUE = 'eg';
const filteredArr = arr.reduce((acc, el) => {
const items = el.items
.filter(n => n.keywords.some(m => m.includes(FILTER_VALUE)))
.map(n => ({ ...n, keywords: [...n.keywords] }));
if (items.length) {
acc.push({ ...el, items });
}
return acc;
}, []);
const $initial = $('.some-div').clone();$('.some-div').replaceWith($initial);$('.some-div').replaceWith($initial.clone());
const find = (arr, id) =>
(Array.isArray(arr) ? arr : []).reduce((found, n) =>
found || (n.id === id ? n : find(n.children, id))
, null);selected() {
return this.active.length
? find(this.users, this.active[0])
: null;
},return-object - тогда в active вместо ключей будут объекты. Соответственно, искать ничего не надо, вычисляемое свойство сократится доselected() {
return this.active[0];
},
const queryIfSelector = f => x =>
f(typeof x === 'string' ? document.querySelector(x) : x);const getTableData = queryIfSelector(table =>
Array.from(table.querySelectorAll('tbody tr'), tr =>
Object.fromEntries(Array.from(tr.querySelectorAll('td'), td => [
td.getAttribute('data-name'),
td.querySelector('input').value,
]))
)
);
// или
const getTableData = queryIfSelector(table =>
Array.prototype.flatMap.call(table.tBodies, tbody =>
Array.prototype.map.call(tbody.rows, tr =>
Array.prototype.reduce.call(tr.cells, (acc, td) => (
acc[td.dataset.name] = td.firstElementChild.value,
acc
), {})
)
)
);
// или
const getTableData = queryIfSelector(table => {
const result = [];
const numHeadRows = table.querySelectorAll('thead tr').length;
for (const input of table.querySelectorAll('tbody input')) {
const td = input.closest('td');
const i = td.parentNode.rowIndex - numHeadRows;
const item = result[i] = result[i] || {};
item[td.attributes['data-name'].value] = input.value;
}
return result;
});const data1 = getTableData('#table1');
const data2 = getTableData(document.querySelector('#table2'));
const Component = Vue.extend(...);document.body.appendChild(new Component(...).$mount().$el);
for (name, items) in cook_book:
print('\n%s:' % name.capitalize())
for (ingredient, quantity, unit) in items:
print('%s, %d %s' % (ingredient, quantity * person, unit))
document.querySelector('textarea').addEventListener('keydown', e => e.preventDefault());<textarea readonly></textarea>
$('table tr').get().reduce((acc, n) => acc.then(() => $.ajax(...)), $.Deferred().resolve());
<select v-model="selected">
<option v-for="item in options" :value="item.value">
{{ item.title }}
</option>
</select>data: () => ({
selected: null,
...
}),
computed: {
monthRate() {
if (this.selected === 'year') {
return this.percent / 12 / 100;
} else if (this.selected === 'month') {
return this.percent / 100;
} else {
return 0;
}
},
},нужно, чтобы в зависимости от выбранной опции, функция срабатывала по разной формуле
monthRate() {
return this.percent * this.selected / 100;
},