function memoize(fn)
{
// Create an object to store cached results.
const cachedResult = {};
// Return an anonymous function.
return function()
{
// Generate a unique key based on the function arguments.
var key = JSON.stringify(arguments);
// Check if the result for the current arguments is not cached.
if (!cachedResult[key])
{
/*
If not cached, compute the result by calling the
product function with the arguments.
*/
cachedResult[key] = fn(...arguments);
}
// Return the cached result.
return cachedResult[key];
}
}
const product=(num1, num2)=>
{
// Intentionally running the costly loop
for(let i=0;i<10000000;i++){}
// Returning the product
return num1*num2;
}
const memoizedProduct=memoize(product)
console.time("1st Call")
console.log(memoizedProduct(22222,12345))
console.timeEnd("1st Call")
console.time("2nd Call")
console.log(memoizedProduct(22222,12345))
console.timeEnd("2nd Call")
//Output of 1st call
274330590
1st Call: 20.973ms
//Output of 2nd call
274330590
2nd Call: 0.278m
/* to the body element */
.noscroll {
overflow: hidden;
}
.overlay {
position: fixed;
overflow-y: scroll;
inset: 0;
place-items: center;
}
[aria-hidden="true"] { display: none; }
[aria-hidden="false"] { display: grid; }
/* this code is not strictly necessary: just to make this demo a bit pleasant */
.overlay div {
width: 80%;
max-width: 650px;
padding: 30px;
background: rgba(255,255,255, .95);
}
.overlay {
background: rgba(40,40,40, .75);
}
* { box-sizing: border-box; }
button { padding: 1.5em 4em; cursor: pointer;}
pre { background: #fafafa; padding: 15px; border: 1px #ccd dashed; }
pre + p { margin: 5vh 0; }
/*
https://kentondejong.medium.com/this-css-1-liner-will-improve-your-flexbox-7e40e977ef5c
*/
.parent {
--gap: 20px;
--columns: 5;
display: flex;
gap: var(--gap);
flex-wrap: wrap;
}
.child {
flex: 0 1 calc((100% / var(--columns)) - var(--gap) + (var(--gap) / var(--columns)));
}
// 0
const obj = [{ id: 1 }, { id: 2 }, { id: 3 }];
obj.forEach((o, i) => {
if (o.id == 2) {
obj.splice(o, 1);
}
});
console.log(obj);
const arr = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Nick' },
];
// 1#
const ids = arr.map(({ id }) => id);
const unique = arr.filter(({ id }, index) =>
!ids.includes(id, index + 1));
// 2#
const unique = arr.filter((obj, index, selfArr) => {
return index === arr.findIndex(o => obj.id === o.id); // arr === selfArr
});
https://bobbyhadz.com/blog/javascript-remove-duplicates-from-array-of-objects
// 3#
const uniqueIds = [];
const unique = arr.filter(element => {
const isDuplicate = uniqueIds.includes(element.id);
if (!isDuplicate) {
uniqueIds.push(element.id);
return true;
}
return false;
});
// [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}]
// ✅ If you need to check for uniqueness based on multiple properties
const arr2 = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'Bob' },
];
const unique2 = arr2.filter((obj, index) => {
return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});
// [
// { id: 1, name: 'Tom' },
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Nick' },
// { id: 2, name: 'Bob' }
// ]
console.log(unique2);
// #4 same as 3# but with Set
const uniqueIds = new Set()
const unique = arr.filter(element => {
const isDuplicate = uniqueIds.has(element.id);
uniqueIds.add(element.id);;
if (!isDuplicate) {
return true;
}
return false;
});
// #5 same as #1
const unique = arr.filter((obj, index) => {
return index === arr.findIndex(o => obj.id === o.id);
});
// #6 same as #5 but with multiple props
const unique2 = arr2.filter((obj, index) => {
return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});
// last duplicate objects
const unique = arr.filter((obj, index) => {
return index === arr.findLastIndex(o => obj.id === o.id);
});
// Map solution
const arr = [
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Tom' },
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Nick' },
{ id: 2, name: 'James' },
];
function removeDuplicateObjects(arr, property) {
return [...new Map(arr.map(obj => [obj[property], obj])).values()];
}
// [ { id: 1, name: 'Alice' }, { id: 2, name: 'James' } ]
console.log(removeDuplicateObjects(arr, 'id'));
/* Same */
const persons= [
{ id: 1, name: 'John',phone:'23' },
{ id: 2, name: 'Jane',phone:'23'},
{ id: 1, name: 'Johnny',phone:'56' },
{ id: 4, name: 'Alice',phone:'67' },
];
const unique = [...new Map(persons.map((m) => [m.id, m])).values()];
// [
// { id: 1, name: 'Tom' },
// { id: 1, name: 'Alice' },
// { id: 2, name: 'Nick' },
// { id: 2, name: 'James' }
// ]
console.log(removeDuplicateObjects(arr, 'name'));
console.log(unique);
const arr = [
'banan',
'apple',
'orange',
'lemon',
'apple',
'lemon',
]
// 1 no duplicities filter
function removeDuplicities(data) {
return data.filter((value, index) => data.indexOf(value) === index)
}
// 1 only duplicities filter
function onlyDuplicities(data) {
return data.filter((value, index) => data.indexOf(value) !== index)
}
// 2 set
[...new Set(arr)]
// 3 forEeach
let unique = []
arr.forEach(item => {
if (!unique.includes(item)) {
unique.push(item)
}
})
// 4 reduce #1
let unique = arr.reduce((acc, curr) => {
if (acc.indexOf(curr) < 0) {
acc.push(curr)
}
return acc
}, [])
// 4 reduce #2
let unique = arr.reduce((acc, curr) => {
return acc.includes(curr) ? acc : [...acc, curr]
}, [])
// 5 prototype #1
Array.prototype.unique = function() {
let unique = []
this.forEach((item) => {
if (!unique.includes(item)) {
unique.push(item)
}
})
return unique
}
// 5 prototype #2
Array.prototype.unique = function() {
return [...(new Set(this))] // or Array.from() instead of [...]
}
let x = [
{
id: 1,
name: 'A'
},
{
id: 2,
name: 'B'
},
{
id: 3,
name: 'C'
},
{
id: 3,
name: 'C'
},
{
id: 2,
name: 'B'
},
]
// 1
let uniqueArray = [];
let idMap = {};
for (let obj of x) {
if (!idMap[obj.id]) {
idMap[obj.id] = true;
uniqueArray.push(obj);
}
}
// 2
let uniqueArray = x.filter((obj, index, self) =>
index === self.findIndex((o) => o.id === obj.id)
);
// 3
let uniqueArray = x.reduce((accumulator, currentValue) => {
if (!accumulator.some(obj => obj.id === currentValue.id)) {
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(uniqueArray)
sanitizedText(src) {
const div = document.createElement('div');
div.innerHTML = src;
const elements = div.querySelectorAll('*');
elements.forEach((element) => {
element.removeAttribute('style');
});
return div.innerHTML;
}
/*
vylepseny priklad o nazev pro v-model
*/
import { ref, watch } from 'vue'
export function useFormValidation(initialValue, propName = 'value') {
const value = ref(initialValue)
const error = ref('')
watch(value, (newValue) => {
if (newValue.length < 3) {
error.value = 'Value must be at least 3 characters'
} else {
error.value = ''
}
})
function validate() {
if (value.value.length < 3) {
error.value = 'Value must be at least 3 characters'
} else {
error.value = ''
}
}
return { [propName]: value, error, validate }
}