Skip to content

Instantly share code, notes, and snippets.

View Chalarangelo's full-sized avatar
💻
JavaScripting

Angelos Chalaris Chalarangelo

💻
JavaScripting
View GitHub Profile
var cacheName = 'mockApp-v1.0.0';
var filesToCache = [
'./',
'./index.html',
'./manifest.json',
'./static/js/bundle.js'
];
self.addEventListener('install', function(e) {
e.waitUntil(caches.open(cacheName)
self.addEventListener('activate', function(e) {
e.waitUntil(caches.keys()
.then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName)
return caches.delete(key);
}));
}));
return self.clients.claim();
});
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function() { console.log('Registered service worker!'); });
}
// This variable is part of the global scope
var globalVariable = 10;
function someFunction(){
// globalVariable is accessible from someFunction,
// as it is part of the global scope
console.log(globalVariable);
}
someFunction(); // Prints 10
// This is a function and it defines its own
// local scope. argumentVariable is part of the
// function's scope, as it is an argument in its
// definition.
function parentFunction(argumentVariable){
// functionVariable and anotherVariable are both
// part of parentFunction's local scope.
var functionVariable = 10;
let anotherVariable = 15;
function someFunction(){
if (true){
// This variable is defined inside these
// curly braces, which means its part of the
// scope of this block and cannot be accessed
// by other parts of someFunction.
let blockVariable = 30;
// However, using the 'var' keyword this variable,
// while defined inside the same block, is part of
function user(username, password){
// Here we use closures to define public functions
// that can access private variables.
return {
getUsername() { return username; },
setUsername(newUsername) {username = newUsername; },
checkPassword(givenPassword) { return password == givenPassword; }
}
}
// Create a function.
function f(x){
return x * x;
}
// Use the function.
f(5); // 25
// Create an anonymous function and assign
// it to a variable.
var g = function(x){
// Definition of our comparison function.
var sortByWeight = function(x,y){
var xW = x.measurement == "kg" ? x.weight : x.weight * 0.453592;
var yW = y.measurement == "kg" ? y.weight : y.weight * 0.453592;
return xW > yW ? 1 : -1;
}
// Just two slightly different lists of data,
// that need to be sorted based on weight.
var firstList = [
// An array of people.
var myFriends = [
{ name: "John", gender: "male" },
{ name: "Kate", gender: "female" },
{ name: "Mike", gender: "male" },
{ name: "Sophie", gender: "female" },
{ name: "Richard", gender: "male" },
{ name: "Keith", gender: "male" }
];