.min(6, passwordMessage) ---> .min(6, () => passwordMessage.value)
public function expose() {
return array_map(fn($n) => $n instanceof Text ? $n->expose() : $n, get_object_vars($this));
}
data: () => ({
items: [ ... ],
filters: [
item => item.status === 'hello, world!!',
item => item.price > 666,
item => item.text.includes('fuck the world'),
],
}),
computed: {
filteredItems() {
return this.filters.reduce((items, filterFn) => items.filter(filterFn), this.items);
},
},
const result = Array.prototype.reduce.call(letter, (acc, n) => (
(n = soundParts[Number.isNaN(+n) ? 'letter' : 'number'][n]) && acc.push(n),
acc
), []);const result = Object
.entries(Object.assign({}, ...Object.values(soundParts)))
.reduce((acc, n) => (letter.includes(n[0]) && acc.push(n[1]), acc), []);
usort($lots, function($a, $b) use($currencyLists) {
$ia = array_search($a['currency'], $currencyLists);
$ib = array_search($b['currency'], $currencyLists);
$t = $ia - $ib;
return $t ? $t : ($a['lotSize'] - $b['lotSize']);
});
data(){ return{ Item: { ...
v-model="item.name"ADD_TO_PRODUCTS({commit}, item){ commit('SET_PRODUCT_TO_STATE', item) },
methods:{ ...mapActions([ 'ADD_TO_PRODUCTS', ]),
@click="ADD_TO_PRODUCTS"
Читая документацию - сложно полностью понять её.
Может ли это означать, что frontend не мое
либо это стандартная ситуация и стоить продолжать?
const result = arr.reduce((acc, n, i, a) => (
(i && n.name === a[~-i].name) || acc.push([]),
acc.at(-1).push(n),
acc
), []);function groupAdjacent(
data,
{
key = n => n,
newGroup = (c, p) => c !== p,
} = {}
) {
const getVal = key instanceof Function ? key : n => n[key];
return Array.prototype.reduce.call(
data,
(acc, n, i) => {
const v = getVal(n, i);
const iGroup = acc[0].length - (i && !newGroup(v, acc[1]));
(acc[0][iGroup] ??= []).push(n);
acc[1] = v;
return acc;
},
[ [], null ]
)[0];
}const result = groupAdjacent(arr, { newGroup: (c, p) => c.name !== p.name });
// или
const result = groupAdjacent(arr, { key: 'name' });
for (let i in goods) { if (discounts.length === 0) { count = goods[i].value * goods[i].amount; } for (let j in discounts) { if (goods[i].name === discounts[j].name) { count = (goods[i].value - goods[i].value * discounts[j].discount) * goods[i].amount; } else { count = goods[i].value * goods[i].amount; } } sum += count; console.log(count, goods[i].name); }
for (const n of goods) {
let s = n.value * n.amount;
for (const m of discounts) {
if (n.name === m.name) {
s *= 1 - m.discount;
break;
}
}
sum += s;
}Возможно есть лучший способ для решения такой задачи.
function totalCost(goods, discounts) {
discounts = Object.fromEntries(discounts.map(n => [ n.name, 1 - parseFloat(n.discount) / 100 ]));
return goods.reduce((acc, n) => acc + n.value * n.amount * (discounts[n.name] ?? 1), 0);
}
let letters = 'АаЕеIiOoUuYy' //Создал переменную со строкой с гласными
if (arg1[i] == letters[j]) { //Если элемент слова равен элементу строки с согласными newArr.push(arg1[i].indexOf()) //То пушу в массив индексы гласных этого слова }
.push(i).const getVowelsIndexes = str =>
Array.from(str.matchAll(/[aeiouy]/gi), n => n.index);const getVowelsIndexes = ((vowels, str) =>
Array.prototype.reduce.call(
str.toLowerCase(),
(acc, n, i) => (vowels.has(n) && acc.push(i), acc),
[]
)
).bind(null, new Set('aeiouy'));const getVowelsIndexes = str => Object
.entries(str)
.filter(n => 'AaEeIiOoUuYy'.includes(n[1]))
.map(n => +n[0]);const getVowelsIndexes = str =>
eval(`[${[...str]
.map((n, i) => /a|e|i|o|u|y/i.test(n) ? `${i},` : '')
.join('')
}]`);
deep: true, сохраняющий данные в localStorage уже есть, так что никаких дополнительных действий предпринимать не придётся.<div id="app">
<div>
<input v-model="newTaskText" @keypress.enter="addTask">
<button @click="addTask">add</button>
</div>
<hr>
<ol v-if="tasks.length">
<li v-for="(n, i) in tasks">
<label :class="{ 'task-checked': n.checked }">
<input type="checkbox" v-model="n.checked">
{{ n.text }}
</label>
<button @click="delTask(i)">del</button>
</li>
</ol>
<strong>Total: {{ tasks.length || 'no tasks fucking exist' }}</strong>
</div>.task-checked {
text-decoration: line-through;
}Vue.createApp({
data: () => ({
newTaskText: '',
tasks: JSON.parse(localStorage.getItem('tasks')) ?? [],
}),
watch: {
tasks: {
deep: true,
handler: val => localStorage.setItem('tasks', JSON.stringify(val)),
},
},
methods: {
addTask() {
const text = this.newTaskText.trim();
if (text) {
this.tasks.push({
text,
checked: false,
});
this.newTaskText = '';
} else {
alert('fuck off');
}
},
delTask(index) {
if (confirm('really?')) {
this.tasks.splice(index, 1);
}
},
},
}).mount('#app');
const getData = type => fetch(`https://jsonplaceholder.typicode.com/${type}`).then(r => r.json());const [ data, setData ] = useState([]);
useEffect(() => {
Promise
.all([ 'posts', 'users' ].map(getData))
.then(([ posts, users ]) => {
const usersObj = Object.fromEntries(users.map(n => [ n.id, n ]));
setData(posts.map(n => ({
post: n,
user: usersObj[n.userId],
})));
});
}, []);
return (
<div>
{data.map(({ post, user }) => (
<div>
<h2>{post.title}</h2>
<h3>{user.name}</h3>
<p>{post.body}</p>
</div>
))}
</div>
);
const className = 'some-link';
const colors = {
En: 'red',
Ru: 'green',
De: 'blue',
};for (const n of document.getElementsByClassName(className)) {
n.style.setProperty('color', colors[n.textContent]);
}document.querySelectorAll(`.${className}`).forEach(function(n) {
n.style.color = this.find(m => m[0].test(n.innerText))?.[1];
}, Object.entries(colors).map(n => [ RegExp(n[0], 'i'), n[1] ]));- RegExp(n[0], 'i')
+ n[0].toLowerCase()- m[0].test(n.innerText)
+ n.innerText.toLowerCase().includes(m[0])
function clone(value) {
const clone = [];
for (const stack = [ [ 0, value, clone ] ]; stack.length;) {
const [ k, v, target ] = stack.pop();
const isObj = v instanceof Object;
target[k] = isObj ? v.constructor() : v;
if (isObj) {
stack.push(...Object.entries(v).map(n => [ ...n, target[k] ]).reverse());
}
}
return clone[0];
}function clone(value) {
const stack = [];
const clones = new Map;
const getClone = v => v instanceof Object
? (clones.has(v) || stack.push([ v, clones.set(v, v.constructor()).get(v) ]),
clones.get(v))
: v;
for (getClone(value); stack.length;) {
const [ source, target ] = stack.pop();
for (const k in source) if (Object.hasOwn(source, k)) {
target[k] = getClone(source[k]);
}
}
return getClone(value);
}как правильнее всего будет это сделать?
options: {
scales: {
y: {
ticks: {
callback: (value, index, values) =>
index > 0 && index < values.length - 1
? ''
: Math[index ? 'max' : 'min'](...values.map(n => n.value)),
...
нужно создать 6 блоков с разными цветами
:style="{ color: bgColor }"Делаю как в документации
v-for="(index, bgColor) in colorArray"