JS utils

JS utils for Arrays and Objects

by jonahe

JavaScript

let test = [{a: 1}, {b: 2}, {c: 3}, {a: 3, c: 5, f: 444}]

let mergeAndSumDuplicates = (result, next) => {
	Object.keys(next).forEach(key => {
  	result.hasOwnProperty(key) ?
    	result[key] += next[key] :
      result[key] = next[key]
  });
	return result;
};

let removeDuplicatesBy = (equalityCheck) => (soFar, next) => {
	if(soFar.some(item => equalityCheck(item, next))) {
  	return soFar;
  } else {
  	return [...soFar, next];
  }
}

let flatten = (total, next) => {
	return [...total, ...next];
};

let groupBy = key => (total, next) => {
	const keyValue = next[key];
	if(!total.hasOwnProperty(keyValue)) {
  	total[keyValue] = [next];
  } else {
  	total[keyValue].push(next);
  }
  return total;
}

const merged = test.reduce(mergeAndSumDuplicates, {});
console.log(merged)
const arr = [1,1,2,3,4,5,6,6]
const a = { hej: ''}, b = { svej: 'eeee'};
const objs = [a, b, { kalle: '1'}, b, b, b, a]
console.log( 
	objs.reduce(removeDuplicatesBy((x, y) => x == y), [])
)


console.log( new Map(Object.entries(merged)).set('apa', 55) )

for(i = arr.length -1; i >= 0; i--) {
	console.log(arr[i])
}

const ok = (a,b,c) => console.log(a,b,c);

console.log( ok.apply(null, [1,2,[3,4]]))

console.log( 
	arr.map( i => [i, 'apa' + i])
  .reduce(flatten, [])
  .filter(i  => typeof i === "string")
)

const persons = [{ name: 'Aaa', age: 30 }, { name: 'Bbb', age: 35 }, { name: 'Aaa', age: 30 }, { name: 'Ccc', age: 30 }, { name: 'Ddd', age: 25 }]
console.log(
	persons
    .reduce(removeDuplicatesBy((x,y) => x.name == y.name), [])
  	.reduce(groupBy('age'), {})
)

const get = path => source => {
	return path
  	.split('.')
    .reduce((result, subPath) => {
    	return result && result[subPath];
    }, source);
}

const nested = { a: { b: { c: [3,4]}}};

console.log( 'get', get('0.0.0.0')([[['apa']]]) );

const compose = (...fns) => arg => {
	return fns
  	.reverse()
    .reduce((result, fn) => {
  	 return fn(result);
  	}, arg);
}

const takeFirstChar = str => str[0];
const prependHello...