A simple todo app in javascript

Asked in Box onsite interview. With a node.js server on backend.

$().ready(function() {
   $('#add').on('click', addTask);
   $('#tasks').on('click', markComplete);
   // Alternative way
   // var tasksElement = document.getElementById('tasks');
   // tasksElement.addEventListener('click', markComplete);
   //document.getElementById('task-input').onkeydown = function(e){
   $('#task-input').on('keydown', function(e) {
       if(e && e.keyCode == 13){
            addTask();
       }
   });

   function renderTask(result) {
        var checkboxContainerId = 'check' + result.id;
        var taskTextId = 'tasktext-' + result.id;
        if (result.done == '1') {
            checkedState = ' checked ';
        } else {
            checkedState = '';
        }
        taskHtml = '
  • '; taskHtml += ''; taskHtml += '' + result.data + '
  • '; $('#tasks').append(taskHtml); } function taskAdded(result) { renderTask(result); $('#task-input').val(''); } function renderResults(results) { results.forEach(renderTask); } function addTask(e) { url = 'http://localhost:9898/todo/tasks/create'; inputData = $('#task-input').val(); if (!inputData) { return; } $.ajax({ url: url, type: "POST", data: {data: inputData} , success: taskAdded, }); } function markComplete(e) { var done; if (e.target && e.target.matches("input.task-checkbox")) { var taskId = $(e.target).attr('task-id'); if ($(e.target).is(":checked")) { done = "1"; } else { done = "-1"; } var editUrl = 'http://localhost:9898/todo/tasks/' + taskId + '/edit'; $.ajax({ url: editUrl, type: "POST", data: {done: done}, success: function(result) { } }); } } var getTasksUrl = 'http://localhost:9898/todo/tasks'; $.ajax({ url: getTasksUrl, type: "GET", success: renderResults, }); } );
    Posted in Javascript | Leave a comment

    System Design Resources

    Grokking the System Design Interview
    https://www.educative.io/collection/5668639101419520/5649050225344512

    Posted in General | Leave a comment

    Atlassian Hackerrank Interview

    1) Implement a method ‘find’ that will find the starting index (zero based) where the second list occurs as a sub-list in the first list. It should return -1 if the sub-list cannot be found. Arguments are always given, not empty.

    Posted in Algorithms | Leave a comment

    Authentication for REST Apis

    https://hashedin.com/2016/07/05/choosing-right-authentication-for-rest-apis/

    Posted in Concepts | Leave a comment

    Combinations of a String

    Implement a function that prints all possible combinations of a string.

    A string “12” is the same as string “21”

    function combine($instr, $outstr, $index)
    {
        for ($i = $index; $i < strlen($instr); $i++)
        {
    
            $outstr = $outstr . $instr[$i];
            echo "$outstr\n";
            combine($instr, $outstr, $i + 1);
            $outstr = substr($outstr, 0, -1);
        }
    }
    
    combine("wxyz", "", 0);
    
    
    Posted in Algorithms | Leave a comment

    Simulate a debounce function

    http://obscurejavascript.tumblr.com/post/115595038489/debounce-in-javascript

    var debounce = function(callback, delay) {
        var timeout = null;
    
        return function() {
            var args = arguments,
                context = this;
    
            clearTimeout(timeout);
            timeout = setTimeout(function() {
                callback.apply(context, args);
            }, delay);
        };
    };
    
    Posted in Javascript | Leave a comment

    Debounce and Throttle in Javascript

    Throttle: the original function be called at most once per specified period.
    Example: while window resizing

    Debounce: the original function be called after the caller stops calling the decorated function after a specified period.
    Example: Validating contents of a text field after using has stopped typing.

    Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.

    Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.

    If you have a function that gets called a lot – for example when a resize or mouse move event occurs, it can be called a lot of times. If you don’t want this behaviour, you can Throttle it so that the function is called at regular intervals. Debouncing will mean it is called at the end (or start) of a bunch of events.

    A far-fetched metaphor, but maybe could also help.

    You have a friend named Chatty who likes to talk with you via IM. Assuming when she talks she sends a new message every 5 seconds, while your IM application icon is bouncing up and down, you can take the…

    Naive approach: check every message as long as it arrives. When your app icon bounces, check. It’s not the most effective way, but you are always up-to-date.
    Throttle approach: you check once every 5 minutes (when there are new ones). When new message arrives, if you have checked anytime in the last 5 minutes, ignore it. You save your time with this approach, while still in the loop.
    Debounce approach: you know Chatty, she breaks down a whole story into pieces, sends them in one message after another. You wait until Chatty finishes the whole story: if she stops sending messages for 5 minutes, you would assume she has finished, now you check all.

    Posted in Javascript | Comments Off on Debounce and Throttle in Javascript

    Trulia On Site Questions

    1) How does Oauth work ?

    2) Explain journey of a URL ?

    3) How does caching work in a CDN? How do you push a new file out to CDN?

    4) Emulate the throttle function()

    // Allow callback to run at most 1 time per 100ms
    window.addEventListener("resize", throttle(callback, 500));
    // Allow callback to run on each resize event
    window.addEventListener("resize", callback2);
    
    function callback ()  { console.count("Throttled");     }
    function callback2 () { console.count("Not Throttled"); }
    
    function throttle (callback, limit) {
        var wait = false;                  // Initially, we're not waiting
        return function () {               // We return a throttled function
            if (!wait) {                   // If we're not waiting
                callback.call();           // Execute users function
                wait = true;               // Prevent future invocations
                setTimeout(function () {   // After a period of time
                    wait = false;          // And allow future invocations
                }, limit);
            }
        }
    }
    
    Posted in Javascript | Leave a comment

    IIFE in Javascript (Immediately Invoked Function Expression)

    http://benalman.com/news/2010/11/immediately-invoked-function-expression/

    Posted in Javascript | Leave a comment

    How to achieve static variable in javascript

    2 Ways :

    1) Make use of the fact that functions are objects and can have properties
    (Even using “this” instead of uniqueID inside the function will do)

    function uniqueID() {
        // Check to see if the counter has been initialized
        if ( typeof uniqueID.counter == 'undefined' ) {
            // It has not... perform the initialization
            uniqueID.counter = 0;
        }
        uniqueID.counter++;
        return (uniqueID.counter);
    }
    
    console.log(uniqueID());
    console.log(uniqueID());
    
    
    

    2) Using closure and function expressions

    var uniqueID = (function() {
       var id = 0; // This is the private persistent value
       // The outer function returns a nested function that has access
       // to the persistent value.  It is this nested function we're storing
       // in the variable uniqueID above.
       return function() { return id++; };  // Return and increment
    })(); // Invoke the outer function after defining it.
    
    console.log(uniqueID());
    console.log(uniqueID());
    
    
    
    Posted in Javascript | Leave a comment