UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

74 lines (52 loc) 1.69 kB
import { Codec } from "./Codec.js"; export class CodecWithFallback extends Codec { /** * * @param {Codec} codecs */ constructor(...codecs) { super(); this.children = codecs.slice(); if (this.children.length < 1) { throw new Error('At least one codec must be provided'); } } async test(data) { const codecs = this.children; const codec_count = codecs.length; for (let i = 0; i < codec_count; i++) { const codec = codecs[i]; const codec_supports_data = await codec.test(data); if (codec_supports_data) { return true; } } return false; } async decode(data) { const codecs = this.children; const codec_count = codecs.length; const errors = []; let result; for (let i = 0; i < codec_count; i++) { const codec = codecs[i]; const codec_supports_data = await codec.test(data); if (!codec_supports_data) { errors.push({ index: i, error: "Codec doesn't support this data" }); continue; } try { result = await codec.decode(data); } catch (e) { errors.push({ index: i, error: e }); continue; } return result; } throw new Error(`All codecs failed, errors: ${errors.map(a => JSON.stringify(a)).join('\n')}`); } }