All files / src/lib fallback.js

0% Statements 0/25
100% Branches 0/0
0% Functions 0/9
0% Lines 0/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87                                                                                                                                                                             
import { newImage } from './tools/image';
 
/**
 * Loads images from server incase of
 * manifest.json or image server can not be loaded.
 * @class
 */
export class Fallback {
  /**
   *
   * @param {{}} owner  An instance of {@link MiniMemory}
   * @param {{}} options width, height and number of images to be
   */
  constructor(owner, options) {
    this.owner = owner;
    this.width = options.width;
    this.height = options.height;
    this.imageCount = options.imageCount;
    /**
     * @description Holds list of Images those returns 404
     * to avoid try to load again.
     */
    this.excludedImages = [];
    this.init();
  }
  /**
   * initialize loading images from picsum.com
   */
  init() {
    const self = this;
    /**
     * @summary Image succesfully  loaded  handler.
     * @param {Event} e Image onload event.
     */
    function imageFound(e) {
      self.owner.game.addImage(e.target);
    }
    /**
     * @summary Image could not loaded error handler
     * @param {Event} e Image onload.
     */
    function imageNotFound(e) {
      e.target.src = self.picsum(self.width, self.height);
    }
 
    self.owner.cardBack.addEventListener('load', () => {
      for (let i = 0; i <= self.imageCount; i++) {
        const img = newImage(
          self.picsum(self.width, self.height),
          imageFound,
          imageNotFound
        );
        self.owner.images.push(img);
      }
    });
 
    self.owner.cardBack.addEventListener('error', (e) => {
      e.target.src = self.picsum(self.width, self.height);
    });
 
    self.owner.cardBack.src = self.picsum(self.width, self.height);
  }
  /**
   * Creates picsum image patterm.
   * @param { integer} w width of requested image.
   * @param {integer} h height of requested image.
   * @return {string} URL
   */
  picsum(w, h) {
    return `https://picsum.photos/${w}/${h}?image=${this.getFreeId()}`;
  }
  /**
   * Returned number should not be in the excludedImages array
   * Save namber in to excludedImages to avoid it to be choosen again.
   * @return {integer} random Integer between 0 - 1000.
   */
  getFreeId() {
    const self = this;
    let rnd = Math.floor(Math.random() * 1000);
    while (self.excludedImages.filter((ex) => ex === rnd).length > 0) {
      rnd = Math.floor(Math.random() * 1000);
    }
    self.excludedImages.push(rnd);
    return rnd;
  }
}