Sugar Helper

Demo, hasArguments() helper to keep sugar methods tidy.

by Aubrey Taylor

HTML

<ol>
    <li>Click "get" then "set" to see the value update.</li>
    <li>Click "get" again to verify value updated.</li>
</ol>
<pre class="output">No output yet.</pre>

<button class="get">Get Foo</button>
<button class="set">Set Foo to 10</button>

CSS

.output {
    height: 20px;
    width: 100%;
    background: lightgray;
    padding: 5px 10px;
}

JavaScript

// Internal reference
_foo = 0;

// Helpers
function hasArguments(args) {
    return args.length > 0;
}

function updateOutput(val) {
    $('.output').html(val);
}

// Getter setters
function setFoo(val) {
    _foo = val;

    // over simplified example, but sometimes
    // its useful to return success from a setter.
    var success = true;
    return success;
}

function getFoo(val) {
    return _foo;
}

// Sugar method
function foo(val) {
    // hasArguments enables a simple ternary to run the getter or setter.
    // method returns value from get or set
    // obviously we're most interested in the get return value
    // but a return value from the setter can be useful too!
    return hasArguments(arguments) ? setFoo(val) : getFoo(val)
}

// Ui handlers

$('.set').on('click', function (e) {
    success = foo(10);

    if (success) {
        updateOutput('set foo to 10! foo now = ' + foo());
    }
});

$('.get').on('click', function (e) {
    updateOutput("fetched foo's value of " + foo());
});