Skip to content

Instantly share code, notes, and snippets.

@interaminense
Last active July 7, 2021 20:37
Show Gist options
  • Save interaminense/d1674c0c890243b596098efdf142a185 to your computer and use it in GitHub Desktop.
Save interaminense/d1674c0c890243b596098efdf142a185 to your computer and use it in GitHub Desktop.
Utils for JS
/**
* Util Create DOM using literal templates
*/
const createElement = tmpl => new DOMParser().parseFromString(tmpl, 'text/html').body.firstChild;
/**
* Util Object Builder
*/
const builder = (newList = []) => {
let list = newList;
return {
create(item) {
list = list.push({...item, id: new Date().getTime()});
return list;
},
read() {
return list;
},
update(newItem, id) {
list = list.map(item => {
if (item.id === id) {
return {...newItem, id: item.id};
}
return item;
});
return list;
},
delete(id) {
list = list.map(item => {
if (item.id !== id) {
return item;
}
}).filter(Boolean);
return list;
}
}
};
/**
* Get Random Integer passing min and max including the both
*/
const getRndInteger = (min, max) => Math.floor(Math.random() * (max - min + 1) ) + min;
/**
* Shuffle Array
*/
const shuffle = array => {
let currentIndex = array.length;
let temporaryValue;
let randomIndex;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment