Skip to content

Instantly share code, notes, and snippets.

@nicolasmendonca
nicolasmendonca / union.js
Last active March 17, 2019 12:38 — forked from Bradshaw/union.js
Joins two arrays while removing duplicate items
Array.prototype.union = ( array ) => {
const concatenated = this.concat( array );
return concatenated.filter( ( item, pos ) => concatenated.indexOf( item ) === pos );
};
// example
[ 'a', 'b', 'c' ].union([ 'b', 'c', 'd', 'e' ]); // [ 'a', 'b', 'c', 'd', 'e' ]
{
"singleQuote": true,
"useTabs": true,
"tabWidth": 2,
"trailingComma": "es5",
"endOfLine": "lf",
"printWidth": 80,
"semi": true
}
const response1 = [
 { id: 1, productName: 'Chair' },
 { id: 2, productName: 'Table' },
];
const requiredResponse1Output = [
 { id: 1, product: { name: 'Chair' } },
 { id: 2, product: { name: 'Table' } },
];
const response1 = [
 { id: 1, productName: 'Chair' },
 { id: 2, productName: 'Table' },
];
const requiredResponse1Output = [
 { id: 1, product: { name: 'Chair' } },
 { id: 2, product: { name: 'Table' } },
];
@nicolasmendonca
nicolasmendonca / 01.js
Last active July 7, 2019 14:52
07-2019-context
const response1 = [
{ id: 1, productName: 'Chair' },
{ id: 2, productName: 'Table' },
];
const requiredResponse1Output = [
{ id: 1, product: { name: 'Chair' } },
{ id: 2, product: { name: 'Table' } },
];
function mapProductName(transactionsArray) {
return transactionsArray
.map(
({ productName, ...rest }) => ({
...rest,
product: { name: productName }
}),
);
}
const response2 = [
{ transactionId: 1, productName: 'Desk' },
{ transactionId: 2, productName: 'Clock' },
];
const requiredResponse2Output = [
{ id: 1, product: { name: 'Desk' } },
{ id: 2, product: { name: 'Clock' } },
];
function mapTransactionIdIntoId(transactionsIarray) {
return transactionsIarray
.map( ({ transactionId, ...rest }) => ({
...rest,
id: transactionId,
}) )
}
function responseMapper(response, mapperFunctions) {
return mapperFunctions.reduce(
(result, mapper) => mapper(result),
response
);
}
// And call it like this
const result1 = responseMapper(response1, [
mapProductName,
const response3 = [
{ purchaseId: 21, productName: 'Bag' },
{ purchaseId: 22, productName: 'Lamp' },
];
const requiredOutput3 = [
{ productId: 31, purchaseId: 21, product: { name: 'Bag' } },
{ productId: 32, purchaseId: 22, product: { name: 'Lamp' } },
];