Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Thursday, December 22, 2016

destructuring in js


arrays

[x,...y] = [1,2,3,4,5,6]
[1, 2, 3, 4, 5, 6]
x
1
y
[2, 3, 4, 5, 6]

 objects

var x2 = {name:"herby",amount:23423,happy:true,getStatus:function(){return this.name + (this.happy?" is happy":" isnt happy" )  }}
/with renaming variable
var {name:newname, getStatus:getit} = x2;
console.log(newname); //herby

console.log(getStatus); // function etc

Wednesday, December 21, 2016

template literals

for template literals use the back tick "`"

console.log(`this is the sum of 8 X 45 :${8 * 45}`)
var x = {name:"herbert"}
console.log(`this is his name:${x.name }`)

Tuesday, December 20, 2016

Classes


class SimpleDate {
    constructor(year, month, day) {
     
        this.dt = new Date(year, month, day);

        this._year = year;
        this._month = month;
        this._day = day;
    }

    addDays(nDays) {
        dt += nDays;
    }
    getDay() {
        return this._day;
    }
}
class ComplicatedDate extends SimpleDate {
    constructor(year, month, day,Hour, Minute) {
        debugger;
    super(year, month, day);
    this.dt.setHours(this.dt.getHours()+Hour);
    this.dt.setMinutes(this.dt.getMinutes()+Minute);

    }
}

c = new     ComplicatedDate(1977,12,19,2,45);

Monday, December 19, 2016

Simple Generator

function* generateId(){
var i  = 0 ;
while(true){yield i++  }
}


const gen = generateId();
console.log(gen.next().value)
 0
console.log(gen.next().value)
 1
console.log(gen.next().value)
 2
console.log(gen.next().value)
 3

Thursday, December 15, 2016

Promises example in JS and JSOM

 function getListItemByID(listName, itemID) {
return new Promise(function(resolve, reject) {
//debugger;
context = SP.ClientContext.get_current();
        web = context.get_web();
        oList = web.get_lists().getByTitle(listName);

        var currentItem = oList.getItemById(itemID);

        context.load(currentItem);
        context.executeQueryAsync(
            function () {
                resolve(currentItem);
            },
            function (sender, args) {
                reject(args.get_message());
            }
        );
});
};


getListItemByID("Milestones",843)
.then(row=>getListItemByID("Process List",row.get_item("Process_x0020_ID")))
.then(row=>console.log(row.get_item("Process_x0020_Name")))
.catch(error=>console.error(error))



Tuesday, December 13, 2016

Sets in JS (and spread operator)

Constructor

s= new Set()
Set {}

Methods

s.add(45)
s.add(34)
Set {45, 34}
s.clear()
Set {}

Using the spread operator to convert a set to an array

let t = new Set([...s].filter(x=>x ==34))
t
Set {34}

using spread to concatenate sets

x = [s,t]
[Set, Set]//unspread
x=[...s,...t]
[45, 34, 34]//spread

Intersect

new Set([...s].filter(x=>t.has(x)))
Set {34}

difference

new Set([...s].filter(x=>!t.has(x)))

Set {45}

Monday, December 12, 2016

Mapping JS

Declare
const testMap = new Map()

set map
testMap.set(1,{name:"boris",cash:345});
testMap.set(2,{name:"tony",cash:45});
testMap.set(3,{name:"peter",cash:5});
Map {1 => Object {name: "boris", cash: 345}, 2 => Object {name: "tony", cash: 45}, 3 => Object {name: "peter", cash: 5}}
properties
testMap.size
3
testMap.has(2)
true
testMap.has(56)
false
methods
testMap.get(3).name
"peter"

for loop
//first item in array is key and second is value
for(let item of testMap){ console.log( item[1].cash)}//value
345
45
5
for(let item of testMap.keys()){ console.log( item)}
1
2

3

Friday, December 9, 2016

Array methods

Using splice to add items in any position

const arr = ['a','b','c','d']
x = arr.splice(2,0,'3')
x will be empty - []
arr will be ["a", "b", "3", "c", "d"]

Add to the beginning of array

arr.unshift(-13)
[-13, "a", "b", "3", "c", "d"]

remove 1st item

arr.shift()
["a", "b", "3", "c", "d"]

For Each

var temp =””
arr.forEach(function (item) {
    if (isNaN(item)) {
        temp += item;
    }
});
temp = "abcd"

mapping

const test =[{name:"herby",cash:23},{name:"boris",cash:456} ]
const cash = test.map(x=>x.cash)
cash = [23, 456]

Every and Some

const test2 =[{name:"herby",cash:23,eyecolor:"brown"},{name:"boris",cash:456} ]
test2.some(x=>x.eyecolor)
true
test2.every(x=>x.eyecolor)
false

Find

returns 1st item
const z = test2.find(x=>{return x.eyecolor === "brown"})
z    {name:"herby",cash:23,eyecolor:"brown"}
const w = test2.find(x=>{return x.cash  > 0})
w   {name:"herby",cash:23,eyecolor:"brown"}

to get multiple items as an array use:

Filter

const t = test2.filter(x=>{return x.cash  > 0})

sort

 ascending

test2.sort((x,z)=>x.cash -z.cash)

descending

test2.sort((x,z)=>z.cash -x.cash)

Aggregating

console.log(test2.reduce((a,c)=>a+=c.cash,0))

479

Tuesday, December 6, 2016

New Parameter Functionality in JS

  1. New Parameter Functionality

    Rest Params

    function testParams( i , ...j){
    var total = 0;
    j.forEach( function(value, index) { total += value; });
    return Math.pow(total,i);
    }
    testParams(2,1,2,3,4)
    100

    Rest Params with Arrow Functions
    function testParams( i , ...j){
    var total = 0;
    j.forEach( value => total += value);
    return Math.pow(total,i);

    }
    testParams(2,1,2,3,4)
    100

    default Params

    function testDefault(i, power =2){
    return Math.pow(i,power );
    }

    testDefault(10)
    100
    testDefault(10,3)
    1000

Monday, December 5, 2016

const in js

  1. new const feature

    in the past there was no real constants in js, everything could be overwritten (even sometimes keywords)
    in ECMAScript6 this has been alleviated

    const in JS means the object can be assigned once
    if you try this

    const i = 45
    i= 0
    console.log(I)



    this will fail
    SyntaxError: Identifier 'i' has already been declared

    with objects member can be assigned afterwards


    const obj2 = {}
    obj2.a ="gg"



    but subsequent
    obj2 = {}
    will fail

    even with const, the only way to have a readonly member of an object is

    var testobj = {};
    Object.defineProperty( testobj , "pseudoconst",
    {
    value: 3,

    writable: false,

    enumerable: true,

    configurable: true
    });


    testobj.pseudoconst
    3
    testobj.pseudoconst = 5//this wont raise an error but wont change the value either
    5
    testobj.pseudoconst
    3

let in js

  1. as Douglas Crockford has said, the worst feature of JavaScript is global variables.
    This has been alleviated greatly by block scoped variables

    consider the following


    var test ="herman"

    {
    test ="boris";
    console.log(test)
    }
    console.log(test)

    or


    var test ="herman"

    {
    var test ="boris";
    console.log(test)
    }
    console.log(test)

    the result will be


    boris
    boris

    However, with the new let keyword

    var test ="herman"

    {
    let test ="boris";
    console.log(test)
    }
    console.log(test)

    the results are now
    boris
    herman

Friday, September 9, 2016

Monday, September 5, 2016

Wednesday, July 20, 2016

javascript style brackets

there is an added benefit of doing brackets thusly

blah {
}

instead of

blah
{
}

because with return statements
return
{
x:67,y:679
}

this will return undefined

example of call setting context

x = {name:"george",children:[{name:"herby",age:46},{name:"herby2",age:47} ,{name:"herby6",age:45} ]}
test = function(){
for (i = 0; i < this.children.length; i++) {
    console.log("Name:" + this.children[i].name + " age:" + this.children[i].age);
}
}
test.call(x);

 Name:herby age:46
 Name:herby2 age:47
 Name:herby6 age:45


btw - what is output when the data is thus
{name:"george",children:[{name:"herby",age:46},{name:"herby",age:46} ,{name:"herby",age:46} ]}

Simple example of closure


s= function(r){
i=89;
return function(){
return i * r;
}
}
s(10)();

Monday, May 19, 2014

only date in javascript

var curdate = new Date();
        curdate.setHours(0,0,0,0);

Monday, May 12, 2014

'Unexpected Token ILLEGAL' Error

I had this once because word sometimes adds the bizarre double quotes