Untitled

 avatar
unknown
javascript
3 years ago
2.0 kB
2
Indexable
/**
 * Description of the algorithm:
 * 
 * 1) We first sanitize the data to make sure the price is converted to float
 * 2) We sort the data 
 * 3) We use a Set to keep track of unique product ids. 
 * 
 * Time-complexity: Single pass to sanitize the data O(N) + To sort the array O(NlogN) + Single pass to process each product O(N) = O(NlogN)
 * 
 * The algorithm written during the interview had time-complexity of O(N^2) because we scanned the entire array for each product id.
 */
const fetchProductsWithCheapestOffer = async () => {

    let productsStream = await fetch('https://api.apify.com/v2/datasets/VuFwckCdhVhoLJJ08/items?clean=true&format=json')
    let products = await productsStream.json()

    const uniqueProductIds = new Set()

    /* Sanitize the data so that the price of a product is converted to a float */
    products = products.map(product => {
        const priceAsFloat = parseFloat(product.price.substr(1))
        return {...product, price: priceAsFloat};
    })

    /* Sort products based on price */
    products.sort((a, b) => {
        if(a.price === b.price) {
            return 0;
        }
        else if(a.price >  b.price) {
            return 1;
        }
        else {
            return -1;
        }
    })
    
    
    // Response JSON object to be sent
    const res = []
    
    products.forEach(product => {
        if(!uniqueProductIds.has(product.productId)) {
            uniqueProductIds.add(product.productId)
            res.push(product);
        }
    });
    
    console.log(res);
    
    /* POST the data back to the API endpoint */
    const postResponse = await fetch("https://api.apify.com/v2/datasets/VuFwckCdhVhoLJJ08/items?clean=true&format=json", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(res),
    })
    const postReponseJson = await postResponse.json();
}
fetchProductsWithCheapestOffer()