vef1-2025

Vefforritun 1 kennd haustið 2025

View the Project on GitHub vefforritun/vef1-2025

Fyrirlestur – Fallaforritun

Vefforritun 1 — TÖL107G

Ólafur Sverrir Kjartansson, osk@hi.is


Fallaforritun


for (let i = 0; i < 10; i++) {
  console.log(i);
}

function repeatLog(n) {
  for (let i = 0; i < n; i++) {
    console.log(i);
  }
}

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}

repeat(3, console.log);
// → 0
// → 1
// → 2

const labels = [];
repeat(5, (i) => {
  labels.push(`Unit ${i + 1}`);
});
console.log(labels);
// → ["Unit 1", "Unit 2", "Unit 3",
//    "Unit 4", "Unit 5"]

Æðri föll – Higher-order functions


function greaterThan(n) {
  return m => m > n;
}
const greaterThan10 = greaterThan(10);
console.log(greaterThan10(11));
// → true

function repeat(n, action) {
  for (let i = 0; i < n; i++) {
    action(i);
  }
}
function unless(test, then) {
  if (!test) then();
}
repeat(3, (n) => {
  unless(n % 2 === 1, () => {
    console.log(n, 'is even');
  });
});
// → 0 is even
// → 2 is even

forEach


function el(name, ...children) {
  const e = document.createElement(name);
  if (Array.isArray(children)) {
    children.forEach((child) => {
      if (typeof child === 'string') {
        e.appendChild(document.createTextNode(child));
      } else if (child) {
        e.appendChild(child);
      }
    });
  }

  return e;
}

Hrein föll – Pure Functions


Kostir fallaforritunnar


Dæmi um abstract aðgerðir


some, every dæmi

const nums = [1, 7, 8, 11];

function belowTen(n) {
  return n < 10;
}

nums.every(belowTen); // false
nums.some(belowTen); // true

reduce dæmi

function sum(nums) {
  return nums.reduce((a, b) => a + b, 0);
}

sum([1, 2, 3, 4, 5, 6, 7, 8, 9]); // 45

map dæmi

// sum eins og í fyrra dæmi
[1, 2, 3, 4, 5, 6, 7, 8, 9]
  .map(i => i * 2)
  .reduce((a, b) => a + b, 0);

// 90

filter dæmi

const colors = [
  'blue',
  'red',
  'darkblue',
  'lightred',
];

colors
  .filter(c => c.indexOf('blue') >= 0);