Thursday, 19 June 2014

JavaScript function that can be called only once

function add(a, b) {
return a+b;
}

function once(func) {
return function () {
var f = func;
func = null;
return f.apply(
this,
arguments
);
};
}

var add_once = once(add);
console.log(add_once(3, 4)); // 7
console.log(add_once(3, 4)); // throws as f is now null

JSFiddle: http://jsfiddle.net/stevenhollidge/uA6TH/


But I prefer the following code as it’s more readable:

function add(a, b) {
return a+b;
}

function once(func) {
var usageCount = 0;

return function () {
if (usageCount === 1) {
throw 'Already used';
}
usageCount += 1;
return func.apply(
this,
arguments
);

}
}

var add_once = once(add);
console.log(add_once(3, 4)); // 7
console.log(add_once(3, 4)); // throws

JSFiddle: http://jsfiddle.net/stevenhollidge/eqnU3/

Wednesday, 18 June 2014

JavaScript Functional Inheritance

Taken from Douglas Crockford:

function gizmo(id) {
return {
id: id,
toString: function () {
return "gizmo " + id;
}
};
}

function hoozit(id) {
var that = gizmo(id);
this.test = function (testid) {
return testid === id;
};
return that;
}

JS Fiddle: http://jsfiddle.net/stevenhollidge/FGbX6/

JavaScript Closures

Slow: digit_name creates the array each time it's invoked

var digit_name = function (n) {
var names = ['zero', 'one', 'two', 'three'];

return names[n];
};

console.log(digit_name(2)); // two

An example of a closure


Fast: digit_name immediately invokes a function and holds the result, a pointer to the array. This is a pointer to a variable that lives on outside of the scope of the function it was created in.


names is closed over the outer function.

var digit_name = (function () {
var names = ['zero', 'one', 'two', 'three'];

return function (n) {
return names[n];
};
}());

console.log(digit_name(2)); // two
JS Fiddle:  http://jsfiddle.net/stevenhollidge/22Ab7/

Tuesday, 17 June 2014

Simple JavaScript Interceptor

The function on line 14 amends an object method to intercept method calls to fire pre and post functions. The object can then continue to be used as normal.


var Calculator = function () {}
Calculator.prototype.Add = function (a, b) {
console.log("Adding a+b");
return a+b;
}

var SuperCalculator = function () {}
SuperCalculator.prototype = new Calculator();
SuperCalculator.prototype.Delete = function(a, b) {
console.log("Deleting a-b");
return a-b;
}

function createInterceptor (key, context, originalFunc, preFunc) {
var interceptor = function () {
preFunc();
var result = originalFunc.apply(context, arguments);
postFunc();
return result;
}
return interceptor;
}

var mySuperCalculator = new SuperCalculator();
var preFunc = function () { console.log("Pre func fired"); }
var postFunc = function () { console.log("Post func fired"); }

for(var key in mySuperCalculator) {
mySuperCalculator[key] = createInterceptor(key, mySuperCalculator, mySuperCalculator[key], preFunc, postFunc);
}

var addResult = mySuperCalculator.Add(1, 2);
console.log("AddResult: " + addResult);

var deleteResult = mySuperCalculator.Delete(2,1);
console.log("DeleteResult: " + deleteResult);

image


JSFiddle: http://jsfiddle.net/stevenhollidge/vb893/

Saturday, 14 June 2014

Setting default values for arguments in JavaScript

function complex (settings){
settings.option1 = (typeof settings.option1 === "undefined") ? "default option 1" : settings.option1;
settings.option2 = (typeof settings.option2 === "undefined") ? "default option 2" : settings.option2;
settings.option3 = (typeof settings.option3 === "undefined") ? "default option 3" : settings.option3;
settings.option4 = (typeof settings.option4 === "undefined") ? "default option 4" : settings.option4;

console.log(settings.option1);
console.log(settings.option2);
console.log(settings.option3);
console.log(settings.option4);
};
complex({option1: 'this is option 1', option3: 'this is option 3'});
image

JS Fiddle:  http://jsfiddle.net/stevenhollidge/w9z2g/

Thursday, 12 June 2014

Export JSON from SQL Server


create procedure [dbo].[GetJSON] (
@schema_name varchar(50),
@table_name varchar(50),
@registries_per_request smallint = null
)
as
begin
if ( ( select count(*) from information_schema.tables where table_schema = @schema_name and table_name = @table_name ) > 0 )
begin
declare @json varchar(max),
@line varchar(max),
@columns varchar(max),
@sql nvarchar(max),
@columnNavigator varchar(50),
@counter tinyint,
@size varchar(10)

if (@registries_per_request is null)
begin
set @size = ''
end
else
begin
set @size = 'top ' + convert(varchar, @registries_per_request)
end
set @columns = '{'

declare schemaCursor cursor for
select column_name
from information_schema.columns
where table_schema = @schema_name
and table_name = @table_name
open schemaCursor

fetch next from schemaCursor into @columnNavigator

select @counter = count(*)
from information_schema.columns
where table_schema = @schema_name
and table_name = @table_name

while @@fetch_status = 0
begin
set @columns = @columns + '''''' + @columnNavigator + ''''':'''''' + convert(varchar(max), ' + @columnNavigator + ') + '''''''
set @counter = @counter - 1
if ( 0 != @counter )
begin
set @columns = @columns + ','
end

fetch next from schemaCursor into @columnNavigator
end

set @columns = @columns + '}'

close schemaCursor
deallocate schemaCursor

set @json = '['

set @sql = 'select ' + @size + '''' + @columns + ''' as json into tmpJsonTable from [' + @schema_name + '].[' + @table_name + ']'
print @sql
exec sp_sqlexec @sql

select @counter = count(*) from tmpJsonTable

declare tmpCur cursor for
select * from tmpJsonTable
open tmpCur

fetch next from tmpCur into @line

while @@fetch_status = 0
begin
set @counter = @counter - 1
set @json = @json + @line
if ( 0 != @counter )
begin
set @json = @json + ','
end

fetch next from tmpCur into @line
end

set @json = @json + ']'

close tmpCur
deallocate tmpCur
drop table tmpJsonTable

select @json as json
end
end

This will do the trick for small json payloads

Sunday, 1 June 2014

Angular List

An Angular list that features bootstrap layout, reads and denormalises JSON data from a text file and has filtering.

Screenshot:

image

Online demo here

Source

Tuesday, 20 May 2014

Text overflow ellipsis

Adds an ellipsis if the text is longer than the available space.

<html lang="en">
<head>
<meta charset="UTF-8">
<style>
p {
text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;
Width: 150px;
}
</style>
</head>
<body>
<p>This text is longer than the space allows</p>
</body>
</html>

CSS3 keyframes

<html lang="en">
<head>
<meta charset="UTF-8">
<style>

#ball {
width: 160px;
height: 160px;
border-radius: 80px;
background: rgb(25,100,150);
position: absolute;
-webkit-animation: bounce 1s infinite;
-moz-animation: bounce 1s infinite;
-o-animation: bounce 1s infinite;
-ms-animation: bounce 1s infinite;
animation: bounce 1s infinite;
}


@-webkit-keyframes bounce {
0% {top: 0;
-webkit-animation-timing-function: ease-in;
}
40% {}
50% {top: 140px;
height: 140px;
-webkit-animation-timing-function: ease-out;
}
55% {top: 160px; height: 120px; border-radius: 70px / 60px;
-webkit-animation-timing-function: ease-in;}
65% {top: 120px; height: 140px; border-radius: 70px;
-webkit-animation-timing-function: ease-out;}
95% {
top: 0;
-webkit-animation-timing-function: ease-in;
}
100% {top: 0;
-webkit-animation-timing-function: ease-in;
}
}

@-moz-keyframes bounce {
0% {top: 0;
-moz-animation-timing-function: ease-in;
}
40% {}
50% {top: 140px;
height: 140px;
-moz-animation-timing-function: ease-out;
}
55% {top: 160px; height: 120px; border-radius: 70px / 60px;
-moz-animation-timing-function: ease-in;}
65% {top: 120px; height: 140px; border-radius: 70px;
-moz-animation-timing-function: ease-out;}
95% {
top: 0;
-moz-animation-timing-function: ease-in;
}
100% {top: 0;
-moz-animation-timing-function: ease-in;
}
}

@-ms-keyframes bounce {
0% {top: 0;
-ms-animation-timing-function: ease-in;
}
40% {}
50% {top: 140px;
height: 140px;
-ms-animation-timing-function: ease-out;
}
55% {top: 160px; height: 120px; border-radius: 70px / 60px;
-ms-animation-timing-function: ease-in;}
65% {top: 120px; height: 140px; border-radius: 70px;
-ms-animation-timing-function: ease-out;}
95% {
top: 0;
-ms-animation-timing-function: ease-in;
}
100% {top: 0;
-ms-animation-timing-function: ease-in;
}
}

@keyframes bounce {
0% {
top: 0;
animation-timing-function: ease-in;
}
50% {
top: 140px;
height: 140px;
animation-timing-function: ease-out;
}
55% {
top: 160px;
height: 120px;
border-radius: 70px / 60px;
animation-timing-function: ease-in;
}
65% {
top: 120px;
height: 140px;
border-radius: 70px;
animation-timing-function: ease-out;
}
95% {
top: 0;
animation-timing-function: ease-in;
}
100% {
top: 0;
animation-timing-function: ease-in;
}
}
</style>
</head>
<body>
<div id="ball"></div>
</body>
</html>

CSS3 Animations

Hover over each of the cards in the deck:

<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="reset.css">
<script src="prefixfree.min.js"></script>
<script src="modernizr.js"></script>
<link rel="stylesheet prefetch" href="http://weloveiconfonts.com/api/?family=fontawesome">
<link rel="stylesheet prefetch" href="http://fonts.googleapis.com/css?family=Ubuntu">
<style>*,
*:after,
*:before {
box-sizing: border-box;
}

body {
overflow: hidden;
background: #c6c6c6;
-webkit-font-smoothing: antialiased;
}

.deck {
position: absolute;
width: 10em;
height: 13em;
top: 50%;
left: 50%;
margin: -6.5em 0 0 -5em;
-webkit-backface-visibility: hidden;
font-family: 'Ubuntu', "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", "Helvetica", "Arial", sans-serif;
text-align: center;
}

.deck__item {
width: 100%;
height: 100%;
position: absolute;
border-radius: .3em;
border: 0.1em solid rgba(0, 0, 0, 0.15);
box-shadow: 0 0 0.3em rgba(0, 0, 0, 0.3), inset 0 6em 6em rgba(255, 255, 255, 0.1);
-webkit-transform-origin: 90% 92%;
transition: .3s;
}
.deck__item:hover ~ .deck__item {
-webkit-transform: rotate(120deg);
}

.deck__item:last-of-type:after {
content: "";
position: absolute;
left: 90%;
top: 92%;
border-radius: 50%;
width: 1.2em;
height: 1.2em;
background: white;
margin: -.6em 0 0 -.6em;
box-shadow: inset 0 1px 1px white, inset 0 -0.3em 0.2em #dddcdb, 0 0 0.6em rgba(0, 0, 0, 0.2);
}

.deck__item:last-of-type:before {
content: "";
position: absolute;
right: .4em;
bottom: .9em;
width: 1.1em;
height: .15em;
background: silver;
background: rgba(0, 0, 0, 0.1);
z-index: 2;
}

.deck__link {
text-decoration: none;
display: block;
color: white;
color: rgba(255, 255, 255, 0.8);
}

.deck__icon {
font-family: 'FontAwesome', sans-serif;
font-size: 4em;
color: black;
color: rgba(0, 0, 0, 0.6);
display: block;
margin: .5em auto;
}

.deck__item--facebook {
background: #3b5998;
-webkit-transform: rotate(-20deg);
}

.deck__item--github {
background: #4183c4;
-webkit-transform: rotate(-10deg);
}

.deck__item--twitter {
background: #00a0d1;
-webkit-transform: rotate(0deg);
}

.deck__item--linkedin {
background: #0e76a8;
-webkit-transform: rotate(10deg);
}

.deck__item--pinterest {
background: #910101;
-webkit-transform: rotate(20deg);
}

.deck__item--googleplus {
background: #db4a39;
-webkit-transform: rotate(30deg);
}
</style>
</head>
<body>
<ul class="deck">
<li class="deck__item deck__item--facebook">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-facebook"></span>
<span class="deck__label">Facebook</span>
</a>
</li>
<li class="deck__item deck__item--github">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-github"></span>
<span class="deck__label">GitHub</span>
</a>
</li>
<li class="deck__item deck__item--twitter">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-twitter"></span>
<span class="deck__label">Twitter</span>
</a>
</li>
<li class="deck__item deck__item--linkedin">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-linkedin"></span>
<span class="deck__label">LinkedIn</span>
</a>
</li>
<li class="deck__item deck__item--pinterest">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-pinterest"></span>
<span class="deck__label">Pinterest</span>
</a>
</li>
<li class="deck__item deck__item--googleplus">
<a class="deck__link" href="#">
<span class="deck__icon fontawesome-google-plus"></span>
<span class="deck__label">Google+</span>
</a>
</li>
</ul>

<script style="display: none;">var __links = document.querySelectorAll('a');function __linkClick(e) { parent.window.postMessage(this.href, '*');} ;for (var i = 0, l = __links.length; i < l; i++) {if ( __links[i].getAttribute('target') == '_blank' ) { __links[i].addEventListener('click', __linkClick, false);}}</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</body>
</html>

CSS3 Backface

Hide the backside of a rotated div element by hovering over the card below.

<html lang="en">
<head>
<meta charset="UTF-8">
<style>
#container {
position: relative;
margin: 10px auto;
width: 120px;
height: 180px;
z-index: 1;
-webkit-perspective: 1000px;
-moz-perspective: 1000px;
-o-perspective: 1000px;
perspective: 1000px;
}
#card {
width: 100%;
height: 100%;
-webkit-transform-style: preserve-3d;
-webkit-transition: all 1.0s linear;
-moz-transform-style: preserve-3d;
-moz-transition: all 1.0s linear;
-o-transform-style: preserve-3d;
-o-transition: all 1.0s linear;
transform-style: preserve-3d;
transition: all 1.0s linear;
}
#container:hover #card, #container.hover_effect #card {
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
transform: rotateY(180deg);
}
.face {
position: absolute;
width: 100%;
height: 100%;
-webkit-backface-visibility: hidden;
-moz-backface-visibility: hidden;
-o-backface-visibility: hidden;
backface-visibility: hidden;
}
.face.back {
-webkit-transform: rotateY(180deg);
-moz-transform: rotateY(180deg);
-o-transform: rotateY(180deg);
transform: rotateY(180deg);
}
</style>
</head>
<body>
<div id="container" class="hover">
<div id="card">
<div class="front face">
<img src="front.png"/>
</div>
<div class="back face">
<img src="back.png"/>
</div>
</div>
</div>
</body>
</html>