Posts

Showing posts with the label JavaScript

Introduction to webshare API (navigator.share)

Image
navigator.share is a JavaScript API providing a sharing interface similar to native apps
webshare API is supported on most updated mobile browsers Including Google chrome for Android
Sharing is done by passing an Object with parameters "url", "text" or "title" to navigator.share function.
For a webshare request to succeed you must supply at lest one of the parameters
navigator.share returns a Promise upon being called "upon
navigator.share({
    "url": document.location,
    "text": "I'm an example",
    "title": document.title
})
.then(resp => console.info("Successfully shared"))
.catch(errors => console.error(errors))

HTML minifier module for Nodejs

HTML minification is a process involving striping off unneeded, abundant or otherwise unused HTML attributes and elements without affecting the webpage appearance.minification is useful for statically genetated 'serverless' web application webpages as it delivers easy to digest minimal webpageshtml-minifier is free and open-source npm nodejs module written in JavaScript for minifying HTML documents, as compared to similar nodejs html minification modules html-minifier proves to be pretty fast, flexible and efficienthtml-minifier module can be used to minify HTML code programmatically or alternatively you can minify HTML code using global commandline moduleNpm module InstallationTo install module in your terminal typenpm i html-minifierTo install commandline version of html-minifier in your terminal type npm i -g html-minifierusage:
html-minifier [options] [files...]options:
--remove-comments
Strip HTML comments--remove-empty-attributes
Remove all attributes with whitespace-onl…

How to remove null elements from array in JavaScript

Every now and then arrays normally tend to have null or otherwise empty elementsArray filter is a specialized JavaScript function for filtering array elements found to be matching a given criteria for example;const arr = ['max', 'duke']In order to remove duke from elements of the array you can do it as follows;arr.filter(name => (name == 'duke' ? false : true))// returns ['max']You can filter empty and false elements as well, using a similar syntax as done above;const arr = ['max', null, 'duke']arr.filter(name => name)
// ['max', 'duke']

How to strip out html using regular expression in JavaScript

Regular expression isn't a very viable solution for manipulating html due to the complexity of html syntax in the browser it's recommended to create dom elements, appending html source code and then manipulating it using built-in dom querySelectors that has few drawbacks especially for environments without a dom take for instance nodejsYou can use regular expression replace function as;const str = "<b>John swana</b>"str.replace(/(<([^>]+)>)/ig, "")// John swanaAnd that's it

Es6 new features summarized round up

Escmascript es2017 or better known as es16 is the edition after the famously popular es15, In this edition there are only two new additional features the exponention operator and Array.prototype.includes() functionexponention operator** Operator is a short hand method used for raising numbers to their powerIts syntax is similar to native operators such as '+' Addition and '-' (minus) for subtractionExample usage
Initially to raise a number to the power you would need to use math library pow function as;Math.pow({number}, {factor})Since es2017 you can simplify the operation above down to simply as;{number} ** {factor}Example as;5 ** 2
// Giving you 25Array.prototype.includes()Array includes is a feature similar to a pre existing function array.indexof() as compared to array.indexof() array.includes() function notably returns a true  boolean on matched value, and false if value not matchedExamples on how to use 'array.includes()' functionThe first argument is the…

unused css rules tree shaking elimination nodejs

Unused css rules elimination process is a lot more like tree shaking done by JavaScript bundlers for instance if you're familiar with how webpack eliminates dead code as a result tree shaking generates a much smaller bundle with only essential codePurifycss is a nodejs npm open source package that eliminates unused css
You can use purifycss to remove excess css from libraries such as bootstrap, materal design lite to name a few,InstallationYou can get "purify-css" npm package from the package manager by typing in your terminal;npm i purify-cssTo install globally add -g flag;npm i -g purify-cssBasic example usage;
You can use css purify global cli package as;Syntax;purifycss {css} {html}Important flags;-m minify output
-o specify output file nameFor example;purifycss *.css *.html -o css.min.cssOutput containg minified css rules will get saved to css.min.css

How to make a Snake Game using JavaScript and html5

Image
I compiled stapes to create a game similar to Nokia developed, popular game called 'snake'

Snake was first developed by Nokia, programmed in 1997 by Taneli Armanto and published on Nokia mobile devices,  It was introduced on Nokia model 6110, 3310 from 2000 and later the game was rebranded as "Snake Xenzia" Included on later mobile phone models

I made a version that is more simplified and more beginners friendly, It's based on the same idea of making a snake that grows as it eats stuff and the score increases as it grows

I'm implementing this whole game in pure vanilla JavaScript and a taste of html5 canvas, In this project the canvas is used as a renderer for the game's visual output

conceptsandinitialideas

I got the idea while doing another retro gaming project, i thought it would be good too if i created this game, from start my plan had been simplicity and making this game easy to implement, So to simplify everything i had a great deal of planning pr…

How to create zip archives in nodejs

I'm going to compile ways in which you can create archives compressed using zip algorithm in nodejs or a similar JavaScript runtime.node-zip is an open source zip archiving utility authord by daraosn and folked from jszip capable of compresding files into a zip archive and extracting zip archives in JavaScript.node-zip is available on npm you can install it in your terminal window by typing;npm install node-zip example usageconst  zip = new require('node-zip')()
zip.file('test.file', 'John Swana')const data = zip.generate({base64:false,compression:'DEFLATE'})
console.log(data)How to unzip a ziparchiveconst zip = new require('node-zip')(data, {base64: false, checkCRC32: true})
console.log(zip.files['test.file'])

How to install tfjs JavaScript library

Image
Tensorflow is a hardware accelerated JavaScript library for building, training, testing and deploying machine learning models on a JavaScript runtime environment.
Installation through html script tag For use within the browser you can link to jsdelivr content delivery network using an html script tag as follows;
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@1.0.0/dist/tf.min.js"></script>
Installation through npm package manager Alternatively you can install a self hosted version of tensorflow from npm, in your terminal type;
npm install '@tensorflow/tfjs'
Installation for tfjs-node on npm tensorflow has two nodejs packages made specifically for nodejs
Installation for '@tensorflow/tfjs-node' This version is a cpu only version it doesn't utilize gpu to do the computing, install tfjs node by typing;
npm install '@tensorflow/tfjs-node'
Installation for '@tensorflow/tfjs-node-gpu' This version is arguably faster than the …

String repeat in JavaScript

String repeat is a function that can be used to multiply a string for a given number of times, its a feature that is closely related to string multiplication operator in Python programming language, as compared to Python's syntax;
("String") * (number of times to repeat) "A" * 3
// returns "AAA"
Something similar may be archived using string repeat function in JavaScript as;
("String").repeat(number Of times to repeat)
For example to triple "A" you can do as;
"A".repeat(3)
Practical example is with lyrics;
const part = "i feel you, "
const lyrics = part.repeat(4) + " A, B, C" // "i feel you, i feel you, i feel you, i feel you, A, B, C"
Further reading;
String.prototype.repeat() MDN

Rest operator in JavaScript

Rest operator is similar to spread operator its an es6 feature that allows converting arguments to an array of values;

Syntax of spread operator is as follows;

function spr(...params) { console.log(params) } spr(1,2,3) // [1, 2, 3] You can use rest operator among other arguments

function sprr(args, ...params) { console.log(params) } spr('foo', 1, 2, 3) // [1, 2, 3] More information:
Restparameters MDN

JavaScript String includes function

String includes is a function introduced to JavaScript in Escmascript 'es6' that returns a boolean true , or false based on the evaluation whether or not a string contains the string passed as an argument to the function For example;


const str = "John swana" str.includes('John') // true str.includes('duke') // false Running string includes testing whether 'John swana' includes John returns trues as it's a fact.

Running the same string against duke returns false duke is not part of the string 'str'

comparison on var, let and const variable declaration

Introduction
let, const and var are keywords used for variable declarations in JavaScript programming language,const and let were newly introduced to the programming language in Escmascript es6 or es2016.Declaration keywords
the syntax of declaring a variable using let keyword is done as;let {variable name} = valuefor const it's done as;const {variable name} = valuesimilarly with var;var {variable name} = valueScope for 'let' and 'const' variables
let and const declared variables are block scoped that means values assigned remain within the block of assignment;
take for instance;if(true) {
   const declaration = "declared"
}console.log(typeof declaration)
// undefinedvalues remain accessible only within the if blockScope for 'var' variables
var declared variables are function scoped so variables declared within a function are only accessible within the function it's self for example;function assign(param){
    var assignment = param;
}assign(&…

Es6 destructuring operator in JavaScript

JavaScript from es6 enables destructuring operation,
In JavaScript destructuring is done using the syntax;
const [elements] = [array] const {properties} = {object}
For instance using Math object as an example destructuring can be done as follows;
Object matching syntax;
const {abs, min, max} = Math;
List matching syntax;
const [max, min, avg] = [10, 1, 5]
Fail-soft destructuring similar to object property look up returns undefined if there's no property matching;
var [item] = [];
item === undefined;
Fail-soft destructuring can also be done with predefined default vslues as follows;
var [item = 1] = [];
item === 1;
More information: MDNDestructuringassignment

How to write a self invoked function in JavaScript

Self invoked functions are function that run on themselves without need to be called, the syntax to create self invoked functions is as follows;

(function(){ // function body })() the runtime will run everything in a self invoked function's body You can pass parameters to the function using the syntax below;
(function(params){     // function body })(params) parameters will be made available to the function as any other argument

JavaScript default parameters

Image
Since es6 its possible to include default function parameters just like other programing languages such as php do, default parameters cut down the need to initially set default Parameters within the code as;
const vec function (x, y){ if(typeof x == "undefined") x = 0; if(typeof y == "undefined") y = 0; return { x, y } }
now the above can be done in a more simple way , using default parameters as;
const vec function (x = 0, y = 0){ return { x, y } } In either of the functions if you omit either of the Parameters your parameter will default to zero ie 0;

How to get first and last character of a string using 'String.startsWith' and 'String.endsWith' in JavaScript

Image
String starts with is an emcscript es6 feature that allows JavaScript developers to test a string if the first character of a string matches the given criteria ,

Take for instance you have a string, you want to test if it starts with characters '#'
const str = "#JavaScript" cons strr = "I love #kotlin" str.startWith('#') // true strr.endsWith('#kotlin') // true strr.startWith('#') // false str.endsWith('#kotlin') // false Both functions return a boolean true for a match and false if there's no match.

endsWith does what startsWith does except that it does it at the end of the string

How to tabulate array key values using console.table

console.table is a function for tabulating arrays key value pairs it retuns a table when given an array as input. const table = Array(5).fill(0) console.table(table) ┌─────────┬────────┐ │ (index) │ Values │ ├─────────┼────────┤ │ 0 │ 0 │ │ 1 │ 0 │ │ 2 │ 0 │ │ 3 │ 0 │ │ 4 │ 0 │ └─────────┴────────┘

How to use 'console.assert' for assertion in JavaScript

console.assert prints text passed as second argument if the first argument returns false;
for example,


const notTrue = false; console. assert(notTrue, 'I\'ts false') // return "it's false" You can use console.assert to perform simple unit tests of your JavaScript application.

const application = function(params){ if(params.num < 10) return false else return true } const instance = new application({ num: 5 }) console.assert(instance, 'number less than ten') // return "number less than ten"

What is strict mode in JavaScript

Strict mode is a ECMAScript 5.1 feature used mainly for testing and debugging. when enabled the JavaScript engine catches more errors among others undeclared variables, duplicate object properties. How to enable strict mode,
In your code include; 'use strict'; You can put the declarative on the top most line anything that comes after it will be handled in a strict manner.