Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
MyLibrary
import _ from 'lodash';
// count duplicates in the array and return the object, where 'key' is a unique value from the array
// and value is a number of duplicates of this value in the array
export function countDuplicates (array) {
const object = {};
array.filter((v, i, a) => i === a.indexOf(v))
.forEach(v => object[v] = object[v] ? object[v] + 1 : 1);
Object.keys(object).forEach(v => {
object[v] = howMany(v, array);
});
return object;
}
// 'closure' is a closure, returning a multilevel object, i.e. () => person.country.city.district
// , where the certain values might be undefined, for example, 'city'
// this function, instead throwing an error, will return undefined for such values
export function exists(closure) {
try { return closure(); }
catch (e) { return undefined; }
}
// how many duplicates of 'value' in 'array'
export function howMany(value, array) {
const regExp = new RegExp(value, 'g');
return (array.join(' ').match(regExp) || []).length;
}
// Take plain one-level JSON object;
// Turn to array, sort in the ascending order;
// Group into object by first letter of array value (turned to Upper Case);
// Arranged for Section List data type with letters as section titles and return this array.
export function jsonToSectionList(object) {
const array = toArrayAndSort(object);
let output = _.groupBy(array, value => value.charAt(0).toUpperCase());
output = _.reduce(output, (res, v, i) => {
res.push({ data: v, key: i });
return res;
}, []);
return output;
}
// sort the values in the 'array' in the order of values in 'order' array
export function sortByOrder (array, order) {
const arrayOfArrays = order.map(v => {
return [...Array(howMany(v, array))].map(undef => v);
});
const tempArray = [];
arrayOfArrays.forEach((subArr, i) => {
let index = order.indexOf(order[i]);
subArr.forEach(duplicate => {
tempArray[index] = duplicate;
index += order.length;
});
});
return tempArray.filter(v => v);
}
// take plain one-level object, turn into array and sort in ascending order
export function toArrayAndSort(object) {
const words = _.map(object, v => {
return v;
});
const sorted = words.sort((a, b) => {
if (a < b) return -1;
else if (a > b) return 1;
return 0;
});
return sorted;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.